0

好的,所以我有一个问题,我需要将一组产品 ID 传递给下面的 sql 语句

$index = 0;
  $products = $cart->get_products();
  for ($i=0, $n=sizeof($products); $i<$n; $i++) {
   $prod = $products[$index]['id'];

 if (strpos($prod,"{")){
 $product = preg_split("^[{}]^",$prod);
 }else{
 $product = $prod;
 }
 }
$product_query = tep_db_query("select cb.products_id, SUM(cb.customers_basket_quantity),SUM(p.products_rate)  from " . TABLE_PRODUCTS . " p INNER JOIN " . TABLE_CUSTOMERS_BASKET . " cb ON p.products_id = cb.products_id   
WHERE cb.customers_id ='" . $customer_id ."'
AND p.products_id IN '".$product ."'
");

结果总是

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Array'' at line 3

select cb.products_id, SUM(cb.customers_basket_quantity),SUM(p.products_rate) from products p INNER JOIN customers_basket cb ON p.products_id = cb.products_id WHERE cb.customers_id ='3' AND p.products_id IN 'Array'

4

3 回答 3

2

(如果您自己制作(而不是 PDO 参数等),请非常小心您插入 SQL 的内容!)

确保 $product 是一个数组:

$product = (array)$product;

然后转义它的值:

$product = array_map('your_db_escape_function', $product);

然后对其进行字符串化:

$product = "'" . implode("', '", $product) . "'";

然后将其添加到查询中:

"... p.products_id IN (" . $product . ")"

在您的代码编辑后,我认为这就是您想要的:

$products = $cart->get_products();
$productIds = array_map(function($product) {
    return (int)$product['id'];
}, $products);
$productIds = implode(', ', $productIds);

$query = tep_db_query("
    select cb.products_id, SUM(cb.customers_basket_quantity),SUM(p.products_rate)
    from " . TABLE_PRODUCTS . " p
    INNER JOIN " . TABLE_CUSTOMERS_BASKET . " cb ON p.products_id = cb.products_id
    WHERE cb.customers_id ='" . $customer_id ."'
    AND p.products_id IN (" . $productIds . ")
");
于 2013-03-02T19:35:37.057 回答
0

使它像这样IN (1, 2, 3, 4, 5)使用implode(',', $product);

于 2013-03-02T19:34:05.600 回答
0

好的,想通了!这是我需要的一个变量,所以它现在读取

$id = $this->rate($id);
   $qty = $cart->count_contents($id);

在我的公式中返回正确的数量!

于 2013-03-02T20:50:33.293 回答