Jump to content

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)

 

 

here's what i did:

 

<?php

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 :)

Thanks digibucc that worked nicely.  PFMaBiSmAd: that would be a cool feature.  Does that depend on what version of php I'm using?

 

no, it has to do with mysql

 

http://dev.mysql.com/doc/refman/5.1/en/insert.html

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.