0

I'm sure this is something stupid but I cannot figure out why I am getting a syntax error with this.

Thank you for taking the time to look at my code

This is the code that builds the query.

$numElements = count($new_array_without_nulls);
$i=1; // Don't add comma to last element
$query = "\"INSERT INTO $db_table SET "; 
foreach ($new_array_without_nulls as $key => $value) {
  $query .= "{$key}"."="."'{$value}'";
  if ($i<$numElements) {
  $query .= ", ";
  }
else{
$query .="\";";
}
  $i++;}
echo "<br />";
echo $query;

This is the output of echo $query. It is also what is written into an external file as I wanted to check for hidden characters:
"INSERT INTO inv_property SET property_type_id='1', address='zzzzzzzzzzzz', state='CA', fund='1', purchase_date='2010-10-27'";

This is the code using the above query that fails with ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"INSERT INTO inv_property SET property_type_id='1', address='zzzzzzzzzzzz', stat' at line 1

//$query="INSERT INTO inv_property SET property_type_id='1', state='CA', fund='1', purchase_date='2010-10-27', purchase_price='999999.00'";
//The above is cut and paste of echo $query
if($result = mysql_query($query)) { 
echo "<h1>Thank you</h1>Your information has been entered into our database for the property at   ".$_REQUEST['address']; 
} else { 
echo "ERROR: ".mysql_error(); 
} 
} else { 
?> 
<?php 
}

The part that has me confused is that if I take the result of the echo and add it as below, the query executes fine and the table is updated. If I take the result of the echo and paste it into MySql window (minus the double quote marks) It executes fine.

$query="INSERT INTO inv_property SET property_type_id='1', state='CA', fund='1', purchase_date='2010-10-27', purchase_price='999999.00'";
//The above is cut and paste of echo $query
if($result = mysql_query($sql)) { 
echo "<h1>Thank you</h1>Your information has been ent ....
2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by david_r
0

Hi,

Check whether you have set the database configuration in this page.

mysql_connect("hostname","username","password");
mysql_select_db("test");
0

Happy to say I have resolved this. Not to happy I spent hours staring at it.

I removed the leading and trailing double quotation marks and the trailing semicolon from the string that $query was set to.

$query = "\"INSERT INTO $db_table SET ";

was changed to:

$query = "INSERT INTO $db_table SET ";

and the else statement that added the "; was removed.

Hopefully someone can benefit from this.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.