Page 1 of 1

Building an insert/update query out of a $_POST set

Posted: Tue May 19, 2009 10:58 am
by rhecker
Firstly, this is a PHP question, not an SQL question, so I did not post it in the database forum.

I always give my form field names the same names as my database fields, so it seems like I should be able to build my query text out of the $_POST array, but I run into two problems, the final element of the array key/value set is the form submit, which should not be included, and the second to the last key/value pair should not take a comma after it. Because the $_POST arrays are associative, not indexed, I can't figure out how to:
1. identify the final submit key and delete it from the set
2. identify the second-to-last key/value pair for special treatment, which in this case is to leave off the comma that will follow all the other key/value pairs.

What I should end up with is the following:

$sql = "UPDATE $tablename SET $keyvaluepairs $lastkeyvaluepair WHERE id='$id'";

This seems like a code snippet that has to have been written a thousand times before. Maybe someone can simply copy and paste their variation of it. I would appreciate it.

Thanks

Re: Building an insert/update query out of a $_POST set

Posted: Tue May 19, 2009 12:53 pm
by jaoudestudios
Something like this...

Code: Select all

 
unset($_POST['submit']); // to remove this element from your array
$set = '';
foreach ($_POST as $k=>$v)
{
  $set .= $k.' = '.$v.', ';
}
$set = rtrim(substr($set, 0, -1));  // will remove trailing white space & the last comma
$q = 'UPDATE '.$table.' SET '.$set.' WHERE....';
 
NB: Dont forget to protect yourself from mysql injection

Re: Building an insert/update query out of a $_POST set

Posted: Tue May 19, 2009 1:24 pm
by rhecker
Thank you Eddie. This is EXACTLY the response I was hoping for.

Rob