I would like to update a SQL
table using PHP
with PDO
. However I keep getting the following error
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:\xampp\htdocs\core\functions\update_projects.php on line 31
I just can't make sense of where I'm going wrong.
$j = 1;
$chunk_count = count($update)/7;
$backwards = array_reverse($update);
$chunks = array_chunk($backwards, 7);
var_dump($chunks[1]);
try {
for($i = 0; $i < $chunk_count; $i++ ) {
$update_project = $db->prepare('
UPDATE projects
SET comments = ?,
contact = ?,
est_end = ?,
est_start = ?,
apm = ?,
pm = ?
WHERE id = ?
');
foreach ($chunks[$i] as $field => $val) {
$update_project->bindValue($j++, $val, PDO::PARAM_STR);
}
$update_project->execute();
}
echo 'Projects Updated';
} catch(PDOException $e) {
die($e->getMessage());
}
If I var_dump($chunks[1])
I see the following values
array(7) { [0]=> string(13) "some comments" [1]=> string(7) "jim doe" [2]=> string(6) "1-1-14" [3]=> string(7) "12-1-13" [4]=> string(8) "jane doe" [5]=> string(7) "jon doe" [6]=> string(2) "16" }
So where is the problem in my code? Any help is appreciated
It's true, SQL parameters start numbering from 1 (I don't know why the owner of that answer deleted it).
The parameter numbering is defined in the SQL/CLI standard, which dates back to the 1980's, before the number zero was invented. ;-)
As for why your code isn't updating, I'd look to make sure the id values are positioned where you expect them. After reversing and chunking the array, if the id value doesn't end up in the right spot, it might try to update rows, but match none.
Here's an alternative way to code this routine:
$backwards = array_reverse($update);
$chunks = array_chunk($backwards, 7);
var_dump($chunks[1]);
try {
$update_project = $db->prepare('
UPDATE projects
SET comments = ?,
contact = ?,
est_end = ?,
est_start = ?,
apm = ?,
pm = ?
WHERE id = ?
');
$n = 0;
foreach ($chunks as $chunk) {
$update_project->execute($chunk);
$n += $update_project->rowCount();
}
echo 'Projects Updated, affected $n rows';
} catch(PDOException $e) {
die($e->getMessage());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.