Reputation: 868
Looked around everywhere and this is driving me mad, trying to do a basic update in PHP using PDO, with variable sized arrays, here is my code:
function Database_Update($table,$set,$where) {
$con = DB_PDO_Connect();
//Create bind array that picks up values as they have places made for them
$bind = array();
//Write SET part of statement, with ? as variable places
$prep = "UPDATE $table SET ";
foreach ($set as $key => $value){
$prep .= $key."=?, ";
$bind[] = $value;
}
$prep = rtrim($prep, " ,") . " ";
//Write WHERE part of statment, with ? as variable places
$prep .= "WHERE ";
foreach ($where as $key => $value){
$prep .= $key . "=?, ";
$bind[] = $value;
}
$prep = rtrim($prep, " ,");
var_dump($prep);
echo('<br>');
var_dump($bind);
echo('<br>');
var_dump($table);
try {
$stmt = $con->prepare($prep);
$stmt->execute($bind);
echo $affected_rows = $stmt->rowCount();
//$a_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $e->getMessage(), E_USER_ERROR);
}
$con = null;
}
is in in the code, the $prep
output looks like this:
string(138) "UPDATE Test SET Group=?, PartName=?, PartNum=?, NumInstock=?, Shelf=?, NumUsed=?, Distributor=?, DistributorPartNum=?, Cost=? WHERE DBid=?"
And the $bind variable looks like this:
array(10) { [0]=> string(0) "" [1]=> string(24) "Bearing C Spherical" [2]=> string(5) "Hello" [3]=> string(1) "5" [4]=> string(27) "Black Bearing Box 2 shelf 3" [5]=> string(1) "0" [6]=> string(3) "FKS" [7]=> string(6) "GE 8 C" [8]=> string(0) "" [9]=> int(6) }
All columns are in TEXT format apart from the BDid column which is in int. Ive had the code running smoothly with un-preared statements but thought I would update it, with the same data in and the same table.
No errors are returned, but no rows are affected.
Upvotes: 0
Views: 132
Reputation: 237847
GROUP
is a reserved word in MySQL, so you have to escape it to use it in a query, in a PDO query just as you would in a normal query. Backticks will do:
So you'd have to change to these lines:
$prep .= "`$key`=?, ";
...
$prep .= "`$key`=?, ";
Upvotes: 1