php - 尽管代码相同,但在一台服务器上出现 SQL 错误,但在另一台服务器上却没有

标签 php mysql codeigniter

我在 MySQL 中有一个名为 comments 的表 -

+-----------+--------------+------+-----+-------------------+----------------+
| Field     | Type         | Null | Key | Default           | Extra          |
+-----------+--------------+------+-----+-------------------+----------------+
| id        | int(11)      | NO   | PRI | NULL              | auto_increment |
| user_id   | int(11)      | NO   |     | 0                 |                |
| data      | varchar(255) | YES  |     | NULL              |                |
| createdOn | timestamp    | NO   |     | CURRENT_TIMESTAMP |                |
+-----------+--------------+------+-----+-------------------+----------------+

我使用 CodeIgniter PHP 框架。我的 PHP 代码在上表中插入一行 -

$comment = null;
if (isset($_POST['comment']) {
    $comment = $_POST['comment'];
}
$comment = mysql_real_escape_string($comment);
$input = array(
         'comment' => $comment,
         );
$data = json_encode($input);
$sql = "insert into comments(data, user_id) values ('$data', $user_id)";
log_message("info", "add sql :: $sql");
$this->db->query($sql);

现在相同的代码部署在两台服务器上。

  • 服务器 1
    PHP 5.3
    MySQL 5.5
  • 服务器 2
    PHP 5.4
    MySQL 5.5

当我在下面输入评论时,会导致 SQL 错误 -

hello'

错误-

Error Number: 1064
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 '321)' at line 1
insert into comments(data, user_id) values ('{"comment":"hello\\'"', 321)
Filename: /home/hussain/workspace/app/CodeIgniter_2.1.0/models/test_model.php
Line Number: 32

我在服务器 1 上遇到上述错误,但在服务器 2 上没有。为什么?

最佳答案

1.使用下面的函数转义查询

  • $this->db->e​​scape_str()
  • $this->db->e​​scape()
  • $this->db->e​​scape_like_str()

    $sql = "INSERT INTO comments (user_id,data) VALUES(".$this->db->escape($userid).",".$this->db->escape($userid).")";   
    

2.查询绑定(bind)

$comment =  $this->input->post('comment');
$row = array('user_id'=>$userid, 'data'=>$data);
$this->db->insert('comments', $row);
log_message('INFO', "SQL : " . $this->db->last_query());

您可以使用以下语句记录最后执行的查询并验证注入(inject)

log_message('INFO', "SQL : " . $this->db->last_query());

关于php - 尽管代码相同,但在一台服务器上出现 SQL 错误,但在另一台服务器上却没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25302642/

相关文章:

php - 如何在后台使用 PHP 和 MySQL 删除数千行?

php - Laravel,将加密的 secret 存储在 MySQL 索引列中

php - Angular - ng-flow如何将字符串与文件一起发送

php - 使用 PDO 将对象条目插入数据库

c# - Visual Studio 2017在调试时尝试使用IP连接到本地Mysql

jquery - 如何添加图像上传以及ajax jquery表单提交

MySQL:创建一个带有外键的表,该外键引用由外键组成的主键

php - mysqli - 我真的需要做 $result->close(); & $mysqli->close();?

php - 学说 2 : select error

php - 在 codeigniter 中选择数据库 - 现在无法选择数据库