Reputation: 3472
I am trying to build a query from the values of an array so far I have,
$itemPlus = $_POST['itemPlus'];
$query = implode(', ', array_map(function($items) {return $items . ' = ' . $items . '-?';}, $items));
// $query = 'hats = hats-?, gloves = gloves-?, scarfs = scarfs-?'
$params = implode(', ', $userCost);
// $params = '10, 7, 9'
$q = $dbc -> prepare("UPDATE items SET " . $query . ", $itemPlus = $itemPlus+1 WHERE id = ?");
$q -> execute(array($params, $account['id']));
It doesn't work, this is my first time trying this and as it doesn't work I am obviously doing something wrong!?
Thanks
Upvotes: 0
Views: 101
Reputation: 270599
Since $params
is a string of values, you cannot make it into an array along with $account['id']
. Instead.use the array that created it $userCost
:
// Start with the $userCost array...
$paramArr = $userCost;
// Add $account['id'] to it
$paramArr[] = $account['id'];
// And pass that whole array to execute()
$q -> execute($paramArr);
Since $itemPlus
is coming from $_POST
, you will need to be sure that is valid input. Since it refers to a column name, it is recommended to use a whitelist for that:
// Check against an array of possible column names:
if (!in_array($_POST['itemPlus'], array('col1','col2','col3','col4',...)) {
// $_POST['itemPlus'] is NOT VALID
// Don't proceed...
}
Upvotes: 2
Reputation: 28891
Your problem (one of them) lies here:
$q -> execute(array($params, $account['id']));
The $params
variable is a comma-delimited string:
// $params = '10, 7, 9'
You want to pass an associate array of params and values to the execute()
method, like this:
$params = array(
'hats-?' => 10,
'gloves-?' => 7,
'scarves-?' => 9
);
// ...
$q->execute($params);
Upvotes: 1