MySQL doesn't take the string value of a PHP variable (With old mysql driver)
228
I have code that looks like this:
$fields = $_POST;
$valueStrings = array();
foreach ($fields as $key => $value) {
array_push($valueStrings, $key . "=" . (string) $value);
// I also tried "$key = $value"
}
$updateRowQuery = "UPDATE ShoppingCart
SET " . implode(',', $valueStrings) . "
WHERE cartID = $cartID";
I get the error:
Invalid query: Unknown column 'test' in 'field list', query is:
UPDATE ShoppingCart
SET shipToSameLocation=1,shipToSameLocation_shippingLocationID=5,shipToSameLocation_shippingMethod=test
WHERE cartID = 1405
If I remove theshipToSameLocation_shippingMethod
field, it works fine. We can see that its valuetest
(other values, too) don't have quotes around despite the (string) casting in the loop.
How can I fix this?
Answer
Solution:
Wrap all values in quotes. You're unnecessarily casting stuff there. MySQL will figure it out for you.