PDA

View Full Version : Dynamic MySQL Update?



CameronDane
05-06-2009, 07:07 PM
I am trying to dynamically update some fields. I managed to dynamically create the table columns and values. However I am stumped on the final update piece.

The problem is that I can only store the variable that contains the columns and values variables from with in the for loop. As such if I put the Update table_name Set... in there it will run that through the for. How do I get the data out of the loop so I can have only one big update?
Here is my code....

for ($d=1; $d < $numfields; $d++) {
$data{$d} =",". $column{$d}."='". $field{$d}."'<br>";

echo $data{$d};
}
//echo $data{$d}; If I do this it grabs the last row?

dataman
05-07-2009, 03:26 AM
You should really consider getting up to speed on the basics of PHP and MySQL.
You will need to open a connection to the MySQL server with update priv's for the user account. After you have done this, you will need to incorporate a line(s) of php code to do an update to the table you are using.

Again, check some of the massive amount of resources on the basics.

-DataMan

CameronDane
05-07-2009, 04:44 AM
Thanks for your candid reply. I have done all that I just assumed that would have been assumptive. I only posted the code that I am having trouble with.

EvilChookie
05-07-2009, 11:27 AM
The SQL update syntax:



UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value


True dynamic updates need to be flexible. Consider:



$query = "UPDATE $table SET ";

foreach($fields as $key => $value){
$query .= $fields[$key] . "= '" . $values[$key] . "', ";
}

$query = trim($query, ", ");
$query .= " WHERE $idField='$id'";


$fields and $values are arrays that are declared beforehand.

So:
$fields = array("Field One", "Field Two", "Field Three");
$values = array($value1, $value2, "Value 3");

The code above loops through each member of the fields array, and adds the appropriate field and value pair to the sql string. Finally, the last ", " is chopped off, since we don't need it!

The result is one valid sql statement that can handle any number of fields dynamically. This what you're looking for?