croakingtoad Posted July 16, 2007 Share Posted July 16, 2007 I am building a mysql query dynamically but when it comes time to execute the query it is only returning the text representation of the variable. I have the following code- for ($i = 0; $i < count($array); $i++) { //removes characters in $chars from $array items $chars = array(" ", "&", "(", ")", "/", "-"); $trim = str_replace($chars, "", $array[$i]); $query1 .= "$trim, "; $query2 .= "'$" . "_POST[$trim]', "; } $query1 = substr("$query1", 0, -2); $query2 = substr("$query2", 0, -2); $query = "INSERT INTO 2007_results (name, email, ip, $query1) VALUES ('$name', '$email', '$ip',$query2)"; //mysql_query($query); //echo mysql_errno($sql) . ": " . mysql_error($sql) . "\n"; //troubleshooting echo $_POST['AllergyImmunology']; echo "<br />Query is - $query<br /><br />"; echo "Query1 is - $query1<br /><br />"; echo "Query2 is - $query2"; The result of this is below- test Query is - INSERT INTO 2007_results (name, email, ip, AllergyImmunology, Anesthesiology, Cardiology) VALUES ('Marty', 'test@test.com', '70.188.11.41','$_POST[AllergyImmunology]', '$_POST[Anesthesiology]', '$_POST[Cardiology]') Query1 is - AllergyImmunology, Anesthesiology, Cardiology Query2 is - '$_POST[AllergyImmunology]', '$_POST[Anesthesiology]', '$_POST[Cardiology]' What I want to see is Query 1 showing the variable values submitted by the user. Instead what I'm seeing is the variable that I have built but that isn't being parsed as a variable (no doubt to my error). How do I insert $query2 into $query and have it parsed so I have the values of the variable I built and not the variable name. Does that make sense? Thanks in advance! Quote Link to comment Share on other sites More sharing options...
trq Posted July 16, 2007 Share Posted July 16, 2007 Didn't I just show you a better way of doing this? Quote Link to comment Share on other sites More sharing options...
croakingtoad Posted July 16, 2007 Author Share Posted July 16, 2007 Apologies, yes you did. I had to go back and reread because I hadn't used your solution but obviously now I see it is the better choice. Here is what you said to use- $fields = array('foo','bar','bob'); $values = array('this is foo','this is bar','this is bob'); $sql = "INERT INTO tbl (" . implode(",",$fields) . ") VALUES ('" . implode("','",$values) . "')"; My $values array is coming from a user submission (ie: $_POST['foo']). How would I implode the $POST vars into the VALUES portion of the sql query? Quote Link to comment Share on other sites More sharing options...
croakingtoad Posted July 16, 2007 Author Share Posted July 16, 2007 I just realized I can substitute $_POST for $values. Works like a charm!!! Thanks so much! Quote Link to comment 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.