dtiu94034 2012-04-17 17:10 采纳率: 0%
浏览 150
已采纳

在mySQL预处理语句中使用变量

Is it possible to use PHP variables inside a prepared mySQL query, such as:

$stmt = $mysqli->prepare("UPDATE table SET $variable_field = ? WHERE field = ?");

It's being used within an ordering system - such that I have a session that stores the carts contents. I won't know the total number of items ordered until the end. So say a customer orders 10 items - I need to insert those values into item_1, item_2, item_3, etc.

What I would like to achieve:

<<connect to DB>>
$x = 0;
while($x < count($order_contents)) {
    $stmt = $mysqli->prepare("UPDATE table SET item_$x = ? WHERE field = ?");
    $stmt->bind_param("ss", $order_contents[$x], $order_number);
    $stmt->execute();
    $x++;
}
<<close DB connection>>

Pretty much something along those lines. Problem is, I can't see that it's allowing me to specify PHP variables directly within the query. Any help or suggestions?

  • 写回答

1条回答 默认 最新

  • dso407787736 2012-04-17 17:13
    关注
    $x = 0;
    while($x < count($order_contents)) {
        $x++;
        $stmt = $mysqli->prepare('UPDATE table SET item_'.$x.' = ? WHERE field = ?');
        $stmt->bind_param("ss", $order_contents[$x], $order_number);
        $stmt->execute();
    }
    

    I also moved the $x++ to the start of the loop since you want to start with item_1.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?