简体   繁体   English

尝试插入序列化数组时出现MySQL语法错误

[英]MySql syntax error while trying to insert serialized array

When I'm trying to do this: 当我尝试执行此操作时:

$query  = "INSERT INTO news ( ";
            $query .= "page_link,title,content,images,date";
            $query .= ") VALUES ( ";
            $query .= "'{$page_link}','{$title}','{$content}',''" . serialize($images_array) . "'','{$date}'";
            $query .= ")";

I give this error : 我给这个错误:

You have an error in your SQL syntax; 您的SQL语法有误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'a:33:{i:0;s:76:\\" http://www.example.com/wp-content/uploads/2016/07/Abc.jpg ' at line 1 检查与您的MySQL服务器版本相对应的手册,以在'a:33:{i:0; s:76:\\“附近使用正确的语法http://www.example.com/wp-content/uploads/2016 /07/Abc.jpg '位于第1行

I'm sure it's for serialize($images_array) because when I remove it other values will be inserted into database. 我确定它用于serialize($images_array)因为当我删除它时,其他值将插入数据库中。
my array contains links of images. 我的数组包含图像链接。

检查这里您是否有多余的单引号'

$query .= "'{$page_link}','{$title}','{$content}','" . serialize($images_array) . "','{$date}'";

Instead of using direct substitution values, you could use below methods to avoid sql injection. 除了使用直接替换值外,还可以使用以下方法来避免sql注入。

Hope this will solve your problem 希望这能解决您的问题

You basically have two options to achieve this: 您基本上有两种选择可以实现此目的:

Using PDO (for any supported database driver): 使用PDO(对于任何受支持的数据库驱动程序):

$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');

$stmt->execute(array('name' => $name));

foreach ($stmt as $row) {
    // do something with $row
}

Using MySQLi (for MySQL): 使用MySQLi(对于MySQL):

$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);

$stmt->execute();

$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // do something with $row
}

Please refer How can I prevent SQL-injection in PHP? 请参阅如何防止PHP中的SQL注入?

Change your Query to this there is a extra '' in your query make it like this, 将您的查询更改为此,在查询中有一个额外的“”,使其像这样,

'" . serialize($images_array) . "' '''。serialize($ images_array)。“'

$query  = "INSERT INTO news ( ";
            $query .= "page_link,title,content,images,date";
            $query .= ") VALUES ( ";
            $query .= "'{$page_link}','{$title}','{$content}','" . serialize($images_array) . "','{$date}'";
            $query .= ")";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM