插入包含撇号(单引号)的数据时,MySQL错误? [英] MySQL error when inserting data containing apostrophes (single quotes)?

查看:103
本文介绍了插入包含撇号(单引号)的数据时,MySQL错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I an insert query contains a quote (e.g. Kellog's), it fails to insert a record.

错误MSG:

您的SQL语法有错误;检查手册 对应于您的MySQL服务器版本以使用正确的语法 在's','玉米片170g','$ 15.90','$ 15.90','$ 14.10','-')'附近 第1行MySQL更新错误:

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.

有什么解决办法吗?

推荐答案

这是您的功能,使用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; 
    } 
}

这篇关于插入包含撇号(单引号)的数据时,MySQL错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆