简体   繁体   English

插入帖子数据时出现mysql错误

[英]mysql error when inserting post data

I dont know where my error is in this mysql query 我不知道我的错误在这个mysql查询中

$sql = "INSERT INTO `events` ( `owner` ,  `title` ,  `tagline` ,  `location` ,  `street` ,  `citytown` ,  `startdate` ,  `enddate` ,  `active`  ) VALUES(  '{$username}' ,  '{$data[title]}' ,  '{$data['tagline']}' ,  '{$data['location']}' ,  '{$data['street']}' ,  '{$data['citytown']}' ,  '{$data['startdate']}' ,  '{$data['enddate']}' ,  '{$data['active']}'  ) "; 
mysql_query($sql) or die(mysql_error()); 

It tells my i have an error in the syntax near... and then outputs part of my data where i have apostrophes 它告诉我我附近的语法有错误...然后输出我有撇号的部分数据

(example: title = Dave's Party) (例如:标题=戴夫的聚会)

You want to escape single quotes in your strings before you insert them into the database. 您需要先在字符串中转义单引号,然后再将其插入数据库。

You'll probably want to use mysql_real_escape_string on each element of your $data array. 您可能需要在$data数组的每个元素上使用mysql_real_escape_string

For example: 例如:

$escaped_data = array();

foreach ($data as $key => $val) {
    $escaped_data[$key] = mysql_real_escape_string($val);
}

$sql = "INSERT INTO `events` ( `owner` ,  `title` ,  `tagline` ,  `location` ,  `street` ,  `citytown` ,  `startdate` ,  `enddate` ,  `active`  ) VALUES(  '{$username}' ,  '{$escaped_data[title]}' ,  '{$escaped_data['tagline']}' ,  '{$escaped_data['location']}' ,  '{$escaped_data['street']}' ,  '{$escaped_data['citytown']}' ,  '{$escaped_data['startdate']}' ,  '{$escaped_data['enddate']}' ,  '{$escaped_data['active']}'  ) "; 
mysql_query($sql) or die(mysql_error());

As an aside, take a look at the PHP documentation for SQL injection . 顺便说一句,请看一下SQL注入的PHP文档。

Be sure that you have all values properly escaped. 确保所有值均已正确转义。

mysql_real_escape_string mysql_real_escape_string

mysql_escape_string($data['title']);

要么

mysql_real_escape_string($data['title'], $dbconn);

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

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