Error in SQL syntax when trying to upload image to BLOB field

时间:2016-04-04 18:25:04

标签: php mysql sql

I have the following code to process form and store the image in a MySQL database.

$name=htmlentities(stripslashes($_POST['fname']));
$pname=htmlentities(stripslashes($_POST['pname']));
$email=htmlentities(stripslashes($_POST['email']));
$phone=htmlentities(stripslashes($_POST['phone']));
$des=nl2br(htmlentities(stripslashes($_POST['description2'])));
$cost=htmlentities(stripslashes($_POST['price']));
$category=htmlentities(stripslashes($_POST['category']));
$date=htmlentities(stripslashes($_POST['date22']));
$image=htmlentities(stripslashes($_POST['pic']));
$imagedata=file_get_contents($image);

$query="INSERT INTO records
VALUES('','$name','$pname','$email','$phone','$cost','$des','$category','$date','$imagedata');";

if ($connect->query($query) === TRUE) {
echo "Inserted! <a href=\"display.php\">Click here to view database     records</a>";
} else {
echo "Error: " . $connect->error;
}

When I run the code I get the following error in the SQL Syntax:

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 'ݤ‰;(IƒiHôBüŸ¤#Žø#&ad„„¹Ì’¼þý…dÀe‘'Ky÷ 𭉈˕¿ffµúßÄe%KÁ€DdѧÑÊÕÂRO÷' at line 2

I have checked the column and its BLOB. I have checked the sequence of columns and they are fine. Not really sure what's going wrong.

1 个答案:

答案 0 :(得分:1)

You have to escape the image content.

There are different ways to achieve that:

1) If the PHP version that you are using is minor thant PHP 5.5 you can use the "mysql_real_escape_string" function.

$query="INSERT INTO records VALUES('','$name','$pname','$email','$phone','$cost','$des','$category','$date','" . mysql_real_escape_string($imagedata) ."');";

2) Encode the image content using the "base64_encode" function, encoding the the content to base64 is going to increase the file size, but is very safe to use.

 $query="INSERT INTO records VALUES('','$name','$pname','$email','$phone','$cost','$des','$category','$date','" . base64_encode($imagedata) ."');";

Remember to decode the content with the "base64_decode" function when you want to read or download the file.

3) Escape the double and single quotes using the "addslashes" function

 $query="INSERT INTO records VALUES('','$name','$pname','$email','$phone','$cost','$des','$category','$date','" . addslashes($imagedata) ."');";

Remember to remove the slashes when the image is read or downloaded with the "stripslashes" function.