Jump to content

Recommended Posts

I don't really know how to explain this question, so I will try with an example. I'm trying to create a script that creates sql insert statements dynamically. This script needs to handle several different arrays that are passed to it from various form validation scripts. The keys in these arrays are identical to the column names in their respective tables. What I need to do is somehow output the actual names of the keys to be used as the column names in the insert statement, and then output the actual values in the array as the values to be inserted.

 

So I want to take an array like this:

$bookarray = array ( 'booktitle' => 'Cat In The Hat',
'price' => '15.99' );

 

And end up with this:

 

insert into books (booktitle, price) values ('Cat In The Hat', 15.99)

 

Without knowing that the incoming keys were booktitle and price.

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/45836-solved-copy-variable-name/
Share on other sites

What you can do is use the alternative form the MySQL insert syntax:

 

"insert into tablename set field = 'value', field1 = 'value';"

 

Then using your array you would get something like this:

<?php
$bookarray = array ( 'booktitle' => 'Cat In The Hat','price' => '15.99' );
$tmp = array();
foreach ($bookarray as $fld => $val)
    $tmp[] = $fld . " = '" . mysql_escape_string($val) . "'";
$query = 'insert into yourtable set ' . implode(',',$tmp);
echo $query; // debug line
$rs = mysql_query($query) or die("Problem with the query: <pre>$query</pre><br>" . mysql_error());
?>

 

Ken

or

 

<?php

$bookarray = array ( 'booktitle' => 'Cat In The Hat',
'price' => '15.99' );

$fn = join (', ', array_keys($bookarray));
$fv = join ("', '", array_values($bookarray));

$sql = "INSERT into book ($fn) VALUES ('$fv')";

echo $sql;
?>

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.