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?
$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.
Related
trying to insert multiple input and get the last id of other table and insert in into this table for foreign key.
tried to remove from the loop and tried to use foor loop
if($result){
$j = 0;
foreach($_POST as $val){
$po_trans_id = "SELECT LAST_INSERT_ID()[$j]";
$po_qty = $_POST['po_qty'][$j];
$po_unit = $_POST['po_unit'][$j];
$po_description = $_POST['po_description'][$j];
$po_unit_price = $_POST['po_unit_price'][$j];
$po_total_amount = $_POST['po_total_amount'][$j];
$payment_terms = $_POST['paymentTerms'][$j];
$user = $_SESSION["username"][$j];
$query = "INSERT INTO request_po (po_trans_id,po_qty,po_unit,po_description,po_unit_price,po_total_amount,totalPrice,user) VALUES ('$po_trans_id' , '$po_qty' , '$po_unit' , '$po_description' , '$po_unit_price' , '$po_total_amount' , '$totalPrice' , '$user')";
$j++;
$result = mysqli_multi_query($link, $query) or die(mysqli_error($link));
}
id like to insert my last id to other table for relational database.
LAST INSERT_ID() is valid SQL. LAST_INSERT_ID()[0] is not, that's PHP notation and has no place in SQL.
What you want is available as insert_id through mysqli itself. You must ensure that each command completed correctly before proceeding or you will potentially create a mess in your database that's difficult to unwind.
To fix this, keep in mind the following:
DO NOT use mysqli_multi_query. This command does not support placeholders and cannot be secured properly.
What you want is to convert this to proper mysqli with prepared statements:
<?php
if ($result) {
$j = 0;
$count = count($_POST['po_qty']);
// Use insert_id property
$po_trans_id = $link->insert_id;
$stmt = $link->prepare("INSERT INTO request_po (po_trans_id,po_qty,po_unit,po_description,po_unit_price,po_total_amount,totalPrice,user) VALUES (? , ?, ?, ?, ?, ?, ?, ?)");
for ($j = 0; $j < $count; $j++) {
$stmt->bind_param('sssssss',
$po_trans_id,
$_POST['po_qty'][$j],
$_POST['po_unit'][$j],
$_POST['po_description'][$j],
$_POST['po_unit_price'][$j],
$_POST['po_total_amount'][$j],
$_POST['paymentTerms'][$j],
$_SESSION["username"][$j]
);
$stmt->execute();
}
}
?>
Where that statement is prepared once and run many times. If you enable exceptions then you can avoid the or die(...) anti-pattern as well.
My problem is that:
I have a users table in MySQL. I made a query with MySQLi which looks like:
if($stmt = $mysqli->prepare("SELECT condition,name,money FROM users WHERE fbid = ?")){
$stmt->bind_param('s',$_SESSION['FBID']);
$stmt->execute();
$stmt->store_result();
$num_of_rows = $stmt->num_rows;
$stmt->bind_result($condition,$name,$money);
while ($stmt->fetch()) {
And here's my problem, because I want different users to add equal usernames to their ids. So, my code is the following:
if($_GET['name']!='' && $money>'500'){
$stmt2 = $mysqli->prepare("UPDATE users SET `condition` = `condition` + 5, `money` = `money` - 5 WHERE fbid = ? AND name = ?");
$stmt2->bind_param("ss", $_SESSION['FBID'],$_GET['name']);
$stmt2->execute();
$stmt2->close();
I want to update only that value in the database where user ID = $_SESSION[fbid] and name = $_GET[name]. So if I have an account with id 1922838445 and I have three names, for example, John, Joe, and Jill and $_GET[name]=='Joe' then update only that value at the same ids. It works until that point that update only the got value, but it does that 3 times... Because of while () maybe??? How can I fix it?
The two code samples have to come one after!! Because of checking the value of money..
There's no need for the first SELECT and the loop, just put the condition on money into the UPDATE query itself.
if ($_GET['name'] != '') {
$stmt = $mysqli->prepare("
UPDATE users
SET condition = condition + 5, money = money - 5
WHERE fbid = ? AND name = ?
AND money > 500")
$stmt->bind_param("ss", $_SESSION['FBID'], $_GET['name']);
$stmt->execute();
}
Try this instead to get only one record:
It gets only the record you need because it has a WHERE clause on both parameters that you plan to update, instead of only a partial match on the fbid like you had before.
Before you were getting 3 records because you had a partial key search, then looping through the records and updating the same record over and over against, regardless of the value of the second part of the key in the record you were looping against.
if($stmt = $mysqli->prepare("SELECT condition,name,money FROM users WHERE fbid = ? AND name = ?")){
$stmt->bind_param("ss", $_SESSION['FBID'],$_GET['name']);
$stmt->execute();
I'am currently working on a project and want to make a simple page where I can edit groups. I had everything working fine in XAMPP and tried uploading it to the server, but it won't affect any rows in the database.This is the statement:
UPDATE user_groups
SET name = 'TEST',
name_short = 'test',
color = 'green',
category = 'MMORPG'
WHERE id = 2
and:
Affected rows (UPDATE): 0
Is the answer. Creating new groups works fine (Local creating and editing works and I did not change anything in the statements since I uploaded both)
This is what the row looks like that I am trying to affect
EDIT:
$sql_update_info = "UPDATE user_groups SET name = '$new_title', name_short = '$new_short', color = '$new_color', category = '$new_cat' WHERE id = $group_id";
$query_update_info = mysqli_query($mysqli, $sql_update_info);
printf("Affected rows (UPDATE): %d\n", mysqli_affected_rows($mysqli));
echo '<br><span style="color:white;">'.$sql_update_info.'</span>';
Is what the PHP part looks like when clicked on the button.
1st : Try to use prepared statement to avoid sql injection.
2nd : Execute() will return true or false so based on that you need to handle the error like below.
$stmt = $mysqli->prepare("UPDATE user_groups SET name = ?, name_short = ?, color = ?, category = ? WHERE id = ?");
$stmt->bind_param('ssssi', $new_title, $new_short, $new_color, $new_cat, $group_id);
//The argument may be one of four types:
//i - integer
//d - double
//s - string
//b - BLOB
//change it by respectively
$r = $stmt->execute();
if(!$r){
echo $stmt->error;
}else{
$row_count= $stmt->affected_rows;
}
$stmt->close();
$mysqli->close();
I want to get the total numbers of records in the comments table to store it in a variable $count and display it. what should I add to the following code?
$stmt = $mysqli->prepare("select count(*) from comments where post_id=?");
$stmt->bind_param('i',$id);
$id = 133;
$stmt->execute();
what should I add to the following code?
this...
$stmt->bind_result($count);
if ($stmt->fetch()) {
echo $count;
}
See http://php.net/manual/mysqli-stmt.bind-result.php
Possibly stupid question, but can not find answer.
I need to get values from two columns of the same row.
And then set variables with each value.
Here I get one value from column Number and then define variable $NumberPostRegister1
$stmt = $db->prepare("SELECT Number FROM 2_1_journal WHERE Number = :Number1");
$stmt->bindParam(':Number1', $row_id1);
$stmt->execute();
$NumberPostRegister1 = $stmt->fetchColumn();
echo $NumberPostRegister1 .' NumberPostRegister1<br>';
Here I get second value from column IfDraft and then define variable $IfDraft1
$stmt = $db->prepare("SELECT IfDraft FROM 2_1_journal WHERE Number = :Number1");
$stmt->bindParam(':Number1', $row_id1);
$stmt->execute();
$IfDraft1 = $stmt->fetchColumn();
echo $IfDraft1 .' NumberPostRegister1<br>';
Two queries and rather long code.
How to do the same using one query and shorter/simpler code?
$stmt = $db->prepare("SELECT IfDraft, Number FROM 2_1_journal WHERE Number = ?");
$stmt->execute(array($row_id1));
list($IfDraft, $Numer) = $stmt->fetch();