如何使用$wpdb准备值数组

时间:2019-05-03 作者:Dan

我正在遍历一系列产品,并希望使用产品SKU创建OR字符串。

据我所知,您传递了一个查询和变量来替换SQL中的占位符。一个简化的例子是这样的。

$sql = "SELECT id, sku FROM document_product 
        WHERE 1=1
        AND sku LIKE %s
        OR sku LIKE %s
        OR sku LIKE %s";

$prep_sql = $wpdb->prepare($sql, [\'42ts\', \'55zb\', \'66bc\']);

$results = $wpdb->query($prep_sql, ARRAY_A);
这是我的理解。所以我让block这样做:

$skus = [];
$skus_like = [];
foreach($matchedProducts as $matchedProduct) {
    $skus[] = $matchedProduct->sku;
    $skus_like[] = "product_sku LIKE %%%s%%";
}

$sql = "SELECT document_id, product_sku
        FROM document_product
        WHERE 1 = 1 AND (" . implode(\' OR \', $skus_like) . ")";

$prep_sql = $wpdb->prepare($sql, $skus);

$product_document_results = $wpdb->query($prep_sql, ARRAY_A);
我要回来了mysqli_query(): Empty query

Edit:当前错误

WordPress database error You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near


\'%WPR2-100-10\\\\\'% 
OR product_sku LIKE %WPR2-100-10\\\\\'-LCD% 
OR product_sku LIKE %WPR\' 

at line 3 for query 

SELECT document_id, product_sku
FROM document_product
WHERE 1 = 1
AND (product_sku LIKE %APR2-100-10\\\\\'% 
OR product_sku LIKE %APTR2-100-10\\\\\'-BCD% 
OR product_sku LIKE %APTR2-100-20\\\\\'% 
OR product_sku LIKE %APTR2-100-20\\\\\'-BCD% 
OR product_sku LIKE %APTR2-30-10\\\\\'% 
OR product_sku LIKE %APTR2-30-10\\\\\'-BCD% 
OR product_sku LIKE %APTR2-30-20\\\\\'% 
OR product_sku LIKE %APTR2-30-20\\\\\'-BCD% 
OR product_sku LIKE %APTR2-300-10\\\\\'% 
OR product_sku LIKE %APTR2-300-10\\\\\'-BCD% 
OR product_sku LIKE %APTR2-300-20\\\\\'% 
OR product_sku LIKE %APTR2-300-20\\\\\'-BCD%) 

made by require(\'wp-blog-header.php\'), require_once(\'wp-includes/template-loader.php\'), include(\'/themes/the-theme/search.php\'), search_documents

1 个回复
最合适的回答,由SO网友:MikeNGarrett 整理而成

不太好。在您的第一个示例中sku LIKE %s 在你的例子中product_sku LIKE \'%{$matchedProduct->sku}%\'. 这不一样。

$wpdb->prepare() 使用sprintf 替换。这就是你得到%s 在第一个查询中。如果你看看sprintf 在specifiers下的文档中,您可以找到替换模式的列表。$wpdb->prepare() 例如,使用相同的说明符%s 对于字符串,%d 对于整数等。

In your case, you probably want to use product_sku LIKE %%%s%%.

为什么要添加额外的% 标志

printf()sprintf() 函数,转义字符不是反斜杠\\ 而是%.

这意味着%% 输出为%%s 输出为42ts (例如)。总的来说,输出如下product_sku LIKE %42ts%.