I have an array of strings in my session which I am trying to store to the database. But I am getting an error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax
My code is as follows:
$improve =$_SESSION['post']['improve'];
if(is_array($improve))
{
$sql = "INSERT INTO student (improve1) values ('%s')";
$valuesArr = array();
$i=0;
for ($i=1; $i <=$childtoen; $i++)
{
$improve_list="";
if ($improve[$i][0]!="")
{
$improve= mysql_real_escape_string( $improve[$i] );
$improve_list = implode( ',', $improve); echo $improve_list; //echo is working Fine
}
$improve_list = mysql_real_escape_string( $improve_list );
$valuesArr[] = "('$improve_list' )";
}
$sql .= implode(',', $valuesArr);
mysql_query($sql,$connection) or exit(mysql_error());
}
What could be the reason as I am also escaping the string? I even tried escaping the imptove_list but no help.
I think you get an error as $sql .= implode(',', $valuesArr);
just append the imploded array to your predefined string and so the SQL-Statement is invalid.
edit: After reading your now posted errors message.
When I understand your script correctly $valuesArr[] = "('$improve_list' )";
is too much. The final result of this would be ('ADHD,ASPERGER')
. I think this will result in a SQL-statement like INSERT INTO student (improve1) values ('('ADHD,ASPERGER')')
And then you have the given error as the '
cuts your SQL.
Easy way if would be to change your base sql to INSERT INTO student (improve1) values %s
if you make sure the result in $valuesArr[]
is always like ('ADHD,ASPERGER')
.
But I would suggest you just store the real values (ADHD, ASPERGER, NEXTVALUE, ANOTHERVALUE, ...) in your array and build the sql like this:
$sql = sprintf($sql, implode(',', $valuesArr));
This would replace the placeholder %s
with the string from the implode. Then you should be save as you avoid the ('
and ')
for each value