0

So I have two arrays, $gDatabaseKeyNames (list of column names) and $gDatabaseKeyValues (a list of variable names containing values from a script). The variable names are generated dynamically so I keep track of them for an insert.

Rather than listing all of the columns and value variables, I tried this

$cols = implode(", ", array_values($gDatabaseKeyNames));
$vals = implode(", ", array_values($gDatabaseKeyValues));

$query = "INSERT INTO pings (survey_id, $cols) VALUES ('$surveyID', $vals)";                              
mysql_query ($query) or die(mysql_error());

But none of my actual values show up in the database (they are inserted as 0s - all my columns are numeric).

If I echo $query, I see this, which is the correct formatting:

INSERT INTO pings (survey_id, latitude, longitude, pingTimestamp) VALUES ('15', '$Dlatitude', '$Dlongitude', FROM_UNIXTIME('$DtimeStamp'))

However, if I change $query to

$query = INSERT INTO pings (survey_id, latitude, longitude, pingTimestamp) VALUES ('$surveyID', '$Dlatitude', '$Dlongitude', FROM_UNIXTIME('$DtimeStamp'));

It works perfectly!

Why isn't PHP interpreting the variables in the implode? How can I fix this?

2 Answers 2

1

I suspect that $cols has the literal value '$Dlatitude', '$Dlongitude', etc.... PHP does not "double-interpolate" strings. It'll replace $cols with its values, but will NOT replace $Dlatitude with that variable's value. In other words, you're literally inserting some strings-that-look-like-PHP-variable-names into your numeric fields.

What is in the $gDatabaseKeyValues/Names arrays?

Sign up to request clarification or add additional context in comments.

2 Comments

$gDatabaseKeyValues = ("latitude", "longitude", ..) $gDatabaseKeyNames = ("'$Dlatitude'", "'$Dlongitude'", ..)
Remove the quotes from around the $Dxxx vars, so their VALUES go into the array, not their names.
0

It's probably caused because of string/number problems. You should consider changing the database engine (Consider PDO) and use prepared statements to bind the parameters to your query the right way.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.