Jump to content

[SOLVED] Problem with dynamic variable


croakingtoad

Recommended Posts

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', '[email protected]', '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!

Link to comment
https://forums.phpfreaks.com/topic/60129-solved-problem-with-dynamic-variable/
Share on other sites

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?

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.