I\'m trying to create a page that allows users change their info in a sql database using PDO. I\'m new to this and I\'m running into an error. I\'m using this as a source: http:
I have simplified the code to illustrate how to create dynamic UPDATE query. This uses "lazy" binding and regular placeholders ?
.
The text inputs are set as a regular array (ie. not associative) of values.
<?php
if(isset($_POST['submit'])){
if (isset($_POST["info"]) && !empty($_POST["user_id"])) {
$query = "UPDATE `users` SET ";
$query_params = array();
$i =1;
foreach ($_POST['info'] as $value) {
// push array with each valid info entry ...
if ($value) {
$query .= "`info".$i. "` = ?,";
array_push($query_params,$value);
}
$i++;
}
$query = rtrim($query, ',');//remove trailing ,
//
$query .= " WHERE `id` = ?";
array_push($query_params,$_POST['user_id']);
//Show query and parameter array Remove after testing
echo $query;
echo "<br>";
print_r($query_params);
// Execute the query
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
}
?>
<form method="POST" action="#">
<input type="text" name="info[]" id="info" value="">
<input type="text" name="info[]" id="info" value="">
<input type="text" name="info[]" id="info" value="">
<input type="text" name="info[]" id="info" value="">
<input type="text" name="user_id" id="user_id" value="">
<input type="submit" name="submit" value="Submit">
Typical result
UPDATE `users` SET `info1` = ?,`info2` = ? WHERE `id` = ?
Array ( [0] => john [1] => smith [2] => johnsmith )