php - 插入包含撇号(单引号)的数据时出现 MySQL 错误?

标签 php mysql

当我的插入查询包含引号(例如 Kellog's)时,它无法插入记录。

错误信息:

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 's','Corn Flakes 170g','$ 15.90','$ 15.90','$ 14.10','--')' at line 1MySQL Update Error:

第一个's',应该是Kellogg's

有什么解决办法吗?

最佳答案

Escape带反斜杠的引号。喜欢 'Kellogg\'s'


这是你的函数,使用 mysql_real_escape_string:

function insert($database, $table, $data_array) { 
    // Connect to MySQL server and select database 
    $mysql_connect = connect_to_database(); 
    mysql_select_db ($database, $mysql_connect); 

    // Create column and data values for SQL command 
    foreach ($data_array as $key => $value) { 
        $tmp_col[] = $key; 
        $tmp_dat[] = "'".mysql_real_escape_string($value)."'"; // <-- escape against SQL injections
    } 
    $columns = join(',', $tmp_col); 
    $data = join(',', $tmp_dat);

    // Create and execute SQL command 
    $sql = 'INSERT INTO '.$table.'('.$columns.')VALUES('. $data.')'; 
    $result = mysql_query($sql, $mysql_connect); 

    // Report SQL error, if one occured, otherwise return result 
    if(!$result) { 
        echo 'MySQL Update Error: '.mysql_error($mysql_connect); 
        $result = ''; 
    } else { 
        return $result; 
    } 
}

关于php - 插入包含撇号(单引号)的数据时出现 MySQL 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7600661/

相关文章:

php - 使用 Ajax 从 MySQL 中删除记录

php - 未初始化的字符串偏移量: 62

php - 使用 PHP 或 MySQL 删除大型列表上的重复项?

mysql - 使用具有相同外键的两列

mysql - 保存时 View 会被重写

php - mysqli_select_db 数据库错误

php - 如何在 PHP 中使对象全局可访问

创建存储过程时 MySQL 错误 #1064

mysql - 谷歌电子表格: Skip empty queries when stacking multiple queries in one sheet

mysql - 如何向表添加递归外键?