John Davidson

php - Mysqli Prepared statement Update Where IN with multiple values

0 comments
Message:


I am trying to update my sql database with the folowing query. What I need is to have the data updated if the id is IN the colomn id. Apart from that I need some other variables to be update for all of these ids. I can do this hardcoded, but how to I add those vairables to this query?


To be exact. In this example I need $NameResult and $NotesResult update for the rows where the colomn 'id' matches the result from $_POST["UpdatedID"]


I cant find a explanation anywhere on how to do this, anyone that can help me with this?


Thise code gives me a error.


syntax error, unexpected '$types29' (T_VARIABLE), expecting ')' 

$NameResult = "NameTest";
$NotesResult = "NotesTest";
$in8 = str_repeat('?,', count($_POST["UpdatedID"]) - 1) . '?';
$types29 = str_repeat('i', count($_POST["UpdatedID"]));
$sql8 = "UPDATE account SET name = ?, notes = ? WHERE id IN (0,$in8)";
$stmt8 = $mysqli->prepare($sql8);
$stmt8->bind_param('s,s'$types29,$RankerResult,$NotesResult,...$_POST["UpdatedID"]);
$stmt8->execute();
$stmt8->close();


My Answer:
$idList = $_POST['idList'];
$NameResult = $_POST['NameResult'];
$NotesResult = $_POST['NotesResult'];

// Create a prepared statement
$stmt = $mysqli->prepare("UPDATE table_name SET Name = ?, Notes = ? WHERE id IN ($idList)");

// Bind the parameters
$stmt->bind_param("ss", $NameResult, $NotesResult);

// Execute the statement
$stmt->execute();

// Close the statement
$stmt->close();

This code will update the 'Name' and 'Notes' columns in the 'table_name' table for all rows where the 'id' column matches any of the values in the $idList array. Make sure to sanitize and validate the input values before using them in the query to prevent SQL injection attacks.

Rate this post

4 of 5 based on 9094 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us