Reputation: 1714
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?
Upvotes: 1
Views: 2539
Reputation: 72642
$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
.
Upvotes: 1