The Form Tools forums are no longer active, but the old posts have been archived here. Please see the Help page on how to get help / report issues.

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Best way to prepare variable(s) for UPDATE query? (mysql/php)
Go easy (still learning).

Just wondering what the best approach would be for dynamically updating a record in mysql using PHP without using a loop when defining the row data as an array (key=column name, value=value).

I'd like to prepare the key and value from the array as a string and run the query once instead of iterating through the array using a loop for each key/value.


PHP Code:
$data = array('col1' => 'one',
'col2' => 'two',
'col3' => 'three'

$str = ????

$query = ("UPDATE table_name SET ".$str." WHERE some_column=some_value"

I can figure out how to do it using a foreach loop; and I can easily prepare a variable when inserting multiple records using php implode function. I just can't figure out what the best approach would be for updating the table in the same fashion.
Nevermind. I apply the loop to the array instead of the query; what a moron! Just goes to show, you can't legislate for stupidity.



PHP Code:
$data = array('col1' => 'one',
'col2' => 'two',
'col3' => 'three'

foreach (
$data as $field => $value) {
$list[] = $field.'='."'".mysql_real_escape_string($value)."'";
$fields implode(', '$list);
$query "UPDATE table_name SET ".$fields." WHERE some_column=some_value"

Forum Jump:

Users browsing this thread: 1 Guest(s)