Click to See Complete Forum and Search --> : Building an SQL UPDATE string from form data


scaiferw
05-26-2007, 03:12 PM
I've had some help reading in data to build an edit form, now I need to ask for some help writing it back to the database.

1) What I want to do is build a SQL SET string to insert into my SQL statement. What I've figured below (using only 2 attributes for the sake of brevity) works except that it doesn't give me the actual POSTed value, it outputs the $_POST... code instead. I'm looking for the values from the form corresponding to the attributes in the array, something along the lines of birthyear="1960", provstate="ON". I learn most of this stuff from examples so I don't yet fully understand the basics. Can anyone tell me where I've gone wrong?


// identify form data elements to be updated
$datalist = array ("birthyear", "provstate");
// initialize string
$attributes = "";
// build list in format 'attribute = "value", attribute = "value", ...'
foreach ($datalist as $attribute) {
$attributes .= "$attribute=\"$thisattrib\", ";
}
// trim trailing comma and space
$attributes = substr( $attributes, 0, -2 );

// write data to database
$sql="UPDATE dmember SET $attributes WHERE id=".$_POST['id'];

$result=mysql_query($sql) or die(mysql_error());

2. In the example above, I manually create array of the attributes to be updated. Is the collection of variables sent from the form available as an array? Is $_POST such an array? If so, how to I differentiate between strings and numeric values so that strings are quoted and values are not as I build the SET string to insert into the SQL statement. Presumably I could create some sort of exclusions array to list those values such as the primary which are passed but not intended to be updated.

Many thanks in advance,

Rob

curious_george
05-27-2007, 01:17 PM
Try changing this line:

$sql="UPDATE dmember SET $attributes WHERE id=".$_POST['id'];

to:

$sql="UPDATE dmember SET $attributes WHERE id='$_POST[\'id\']'";

or:

$p = $_POST[\'id\'];
$sql="UPDATE dmember SET $attributes WHERE id='$p'";

Sheldon
05-27-2007, 04:58 PM
or $sql="UPDATE dmember SET $attributes WHERE id='{$_POST['id']}' ";

scaiferw
05-28-2007, 06:46 AM
Thanks for your responses.

Actually, it's the building of the $attribute string where I'm having trouble. I can't get this to work:

// identify form data elements to be updated
$datalist = array ("birthyear", "provstate");
// initialize string
$attributes = "";
// build list in format 'attribute = "value", attribute = "value", ...'
foreach ($datalist as $attribute) {
$attributes .= "$attribute=\"$thisattrib\", ";
}


Any ideas?

Cheers,

Rob