hukadeeze Posted April 6, 2007 Share Posted April 6, 2007 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. Quote Link to comment https://forums.phpfreaks.com/topic/45836-solved-copy-variable-name/ Share on other sites More sharing options...
kenrbnsn Posted April 6, 2007 Share Posted April 6, 2007 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 Quote Link to comment https://forums.phpfreaks.com/topic/45836-solved-copy-variable-name/#findComment-222704 Share on other sites More sharing options...
Barand Posted April 6, 2007 Share Posted April 6, 2007 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; ?> Quote Link to comment https://forums.phpfreaks.com/topic/45836-solved-copy-variable-name/#findComment-222712 Share on other sites More sharing options...
hukadeeze Posted April 6, 2007 Author Share Posted April 6, 2007 Thanks for the responses, I'm going to take a look tomorrow Quote Link to comment https://forums.phpfreaks.com/topic/45836-solved-copy-variable-name/#findComment-222733 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.