Jump to content

use a foreach statement to add a record to a table


Recommended Posts

I have some code that will update a record and is generic, meaning any POST variables can be used - whatever you have on the form.  See below:

$set = array();
foreach($_POST as $field => $value){
    $field = mysql_real_escape_string($field);
    $value = mysql_real_escape_string($value);
    $set[] = "`{$field}` = '{$value}'";

$query .= implode(", ",$set) . " WHERE $id_name = '".$id."' LIMIT 1";

mysql_query($query) or die(mysql_error());


My question is, how would I modify this to insert a NEW record (not update an existing one).  I'm not sure how to order this within a foreach statement because the add query has a different form: insert into tabel (all the fieldnames here) VALUES (all the values here)



Link to comment
Share on other sites

here's what i did:



foreach ($entry as $key=>$value){
if ($value != '' && $value != 'Submit'){
$cols .= mysql_real_escape_string($key). ', ';
$vals .= '\''. mysql_real_escape_string($value). '\', ';

$columns = substr($cols,0,-2); // trim trailing "'," , 
$values = substr($vals,0,-2);

$sql="INSERT INTO table ( $columns )VALUES ( $values )";


i'm sure there are other ways to handle the trailing "',", but this works for me :)

Link to comment
Share on other sites


This topic is now archived and is closed to further replies.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.