PDA

View Full Version : Creating INSERT statement from an array


erdinc
05-21-2006, 02:40 AM
Hi

I'm looking for a way to create INSERT statements for mysql using values stored in an array and I'm not sure how to go about with this. In theory I would like to use:


<?php
foreach($_POST as $key => $item) {
$key = $_POST[$key];
}
?>


to convert the posted vars to simplified variables. I would then like to be able to put them into an array and use it to to create the SQL statements (eg. INSERT statement).

I want to achieve this because the number of form fields may vary and i wouldn't want to type in all the fields and variables inside the INSERT statment.

I hope i've explained what i want to do clearly and would welcome any help on this.

Thanks
Erdinc

mic2100
05-21-2006, 09:00 AM
<?php
foreach($_POST as $key => $item) {
array($value[$key] = $item);
}

?>

that would put all of the values in to an array
now you will ave to make the insert statement from the values


$insertValues = '(';
foreach($value as $key => $item)
{

$insertValues .= $item.", ";

}
$insertValues = substr($insertValues, 0, -2);
$insertValues .= ')';

insertSQL = "INSERT INTO tbl_name (field1, field2, field3, etc) VALUES ".$insertValues;


Hopefully this will help you

GJay
05-21-2006, 11:19 AM
there isn't a lot of point putting $_POST into another array, but if you were, then
$value=$_POST
is surely a better way?

You could add to the above by using keys of the array to determine the fields that you're inserting into, in pretty much the same way.

erdinc
05-22-2006, 12:34 AM
Thanks mic2100 that's almost what I want. Is there also a way to put the field list from an array like the insertValues?

Something similar to this:

insertSQL = "INSERT INTO tbl_name (".$fieldList.") VALUES ".$insertValues;

I understand the code for the insertValues in your post. Could you rewrite this code so it can give me the fieldList as well as the insertValues?

Many thanks for your help.

Also thanks to GJay for his reply too.

marek_mar
05-22-2006, 02:12 PM
http://www.codingforums.com/showthread.php?t=75107