Reputation: 7576
I have an array where the keys represent each column in my database. Now I want a function that makes a mysql update query. Something like
$db['money'] = $money_input + $money_db;
$db['location'] = $location
$query = 'UPDATE tbl_user SET ';
for($x = 0; $x < count($db); $x++ ){
$query .= $db something ".=." $db something
}
$query .= "WHERE username=".$username." ";
Upvotes: 0
Views: 527
Reputation:
foreach($array as $attr => $val)
$items[] = "$attr='$val'";
mysql_query("INSERT INTO table SET ".implode(',', $items));
Upvotes: 0
Reputation: 816462
You want foreach
:
$values = array();
foreach($db as $column => $value){
$values[] = $column . "='" . mysql_real_escape_string($value) . "'";
}
$query .= implode(',', $values);
But this will set all values as strings (not sure if MySQL makes automatic conversion), you might want to test with is_numeric
first:
if(!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value) . "'";
}
$values[] = $column . "=" . $value;
Update:
Whenever you set string values in a query, you have to put them into quotation marks. Hence you have to write:
$query .= "WHERE username='".$username."'";
(note the single quotation marks).
Using sprintf
can make the whole thing much clearer.
Upvotes: 3
Reputation: 54445
You could use array_keys to extract the names of the array elements and then simply use something like...
$query .= $keys[$x] . '="' . mysql_real_escape_string($db[$keys[$x]]) .'" ';
...within the for loop.
(I've presumed the presence of a...
$keys = array_keys($db);
... after you've defined the $db values in the above.)
That said, I'm really not sure I'd recommend such a "one size fits all" approach.
Upvotes: 0
Reputation: 38135
something like this:
function mysql_update_array($table, $data, $id_field, $id_value) {
foreach ($data as $field=>$value) {
$fields[] = sprintf("`%s` = '%s'", $field, mysql_real_escape_string($value));
}
$field_list = join(',', $fields);
$query = sprintf("UPDATE `%s` SET %s WHERE `%s` = %s", $table, $field_list, $id_field, intval($id_value));
return $query;
}
Please note that the code is NOT mine!
Upvotes: 0