我知道之前有人问过这件事。虽然看了我能找到的所有解决方案,但没有任何效果。查询1获取并返回正确的值。当我将这些值传递给查询2时,我遇到了问题。值也是数字而不是字符串。我将变量包装在引号中,没有引号,连接等
这是我的代码:( QUERY 2不起作用)
//QUERY 1 - WORKS FINE, RETURNS VALUES
$sql = "SELECT item_id, quote_id, product_id FROM sales_flat_quote_item WHERE quote_id = $quote_id";
$result = $mysqli->query($sql);
while($tagline_values = $result->fetch_assoc()){
$item_id = $tagline_values['item_id'];
$product_id = $tagline_values['product_id'];
}
echo '<span>' . $item_id . ' - ' . $product_id . '</span>'; // THIS ECHOS GOOD VALUES
// QUERY 2 - DOES NOT ACCEPT VALUES FROM QUERY 1
$sql = "SELECT * FROM sales_flat_quote_item_option WHERE item_id = $item_id AND product_id = $product_id AND code LIKE 'option_779'";
$result = $mysqli->query($sql);
while($tagline_values = $result->fetch_assoc()){
$value = $tagline_values['value'];
echo $value; // NOTHING ECHOS
}
如果我手动设置$ item_id和$ product_id,则QUERY 2可以正常工作。
//This Works
$item_id = 12334;
$product_id = 2324;
$sql = "SELECT * FROM sales_flat_quote_item_option WHERE item_id = $item_id AND product_id = $product_id AND code LIKE 'option_779'";
我已经用尽了所有关于为什么这不起作用的想法。
答案 0 :(得分:1)
您应该使用参数绑定而不是插值。
$st1 = $mysqli->prepare("SELECT item_id, quote_id, product_id FROM sales_flat_quote_item WHERE quote_id = ?");
$st1->bind_param('i',$quote_id);
$st1->execute();
$st1->bind_result($item_id, $quote_id, $product_id);
$st1->fetch();
$st2 = $mysqli->prepare("SELECT * FROM sales_flat_quote_item_option WHERE item_id = ? AND product_id = ? AND code LIKE 'option_779'");
$st2->bind_param('ii',$item_id, $product_id);
$st2->execute();
$result = $st2->get_result();
while($tagline_values = $result->fetch_assoc()){
$value = $tagline_values['value'];
echo $value;
}
或者,您可以使用LEFT JOIN
将两个查询压缩为单个语句。
以下内容应该有效:
$sql = <<<SQL
SELECT
`item`.quote_id,
`option`.*
FROM
`sales_flat_quote_item` AS `item`
LEFT JOIN
`sales_flat_quote_item_option` AS `option`
ON `item`.item_id = `option`.item_id
AND `item`.product_id = `option`.product_id
WHERE `item`.quote_id = ?
AND `option`.code LIKE 'option_779'
SQL;
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i',$quote_id);
$stmt->execute();
$result = $stmt->get_result();
while($tagline_values = $result->fetch_assoc()){
echo $tagline_values['item_id'];
echo $tagline_values['product_id'];
echo $tagline_values['value'];
}
答案 1 :(得分:0)
答案 2 :(得分:0)
通过查看你的sql 2
$sql = "SELECT * FROM sales_flat_quote_item_option WHERE item_id = $item_id AND product_id = $product_id AND code LIKE 'option_779'";
提供了两个变量,即$item_id
和$product_id
尝试回应它们,确保它们达到查询。
同时检查每一步的错误,尤其是像
if($result = $mysqli->query($sql)){ //blah blah } // or ypu can use even `mysqli_error()` function
else //error