Jump to content

[SOLVED] Copy Variable Name


hukadeeze

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;
?>

Archived

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.