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
Building an insert/update query out of a $_POST set
Moderator: General Moderators
- jaoudestudios
- DevNet Resident
- Posts: 1483
- Joined: Wed Jun 18, 2008 8:32 am
- Location: Surrey
Re: Building an insert/update query out of a $_POST set
Something like this...
NB: Dont forget to protect yourself from mysql injection
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....';
Re: Building an insert/update query out of a $_POST set
Thank you Eddie. This is EXACTLY the response I was hoping for.
Rob
Rob