PHP MYSQL 插入数据时出错

标签 php mysql mysqli kohana

我收到以下错误:

2016-04-26 15:11:56 --- DEBUG: Error ocurred where inserting user data to the legacy db :Database_Exception [ 0 ]: [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 ')' at line 1 ~ APPPATH/classes/database/mysqli.php [ 179 ]

对于 php 查询:

$result = $usdb->query(Database::INSERT, "INSERT INTO users (id, `password`, group_id , active, created, updated) VALUES ({$user['id']}, {$user['password']}, {$user['group_id']}, {$user['active']}, {$user['created']}, {$user['updated']})");

列类型如下:

id : int AI PK
password : varchar

group_id : int

active : tinyint

created : int

updated : int

最佳答案

您需要在 SQL 查询中用单引号 ' 将您的值括起来,假设它们是数据库中的字符串(不是整数)。

列和表引用可以用反引号封装,尽管它们不是必须的,假设它们没有使用保留关键字。另一方面,值通常需要用单引号括起来(当然,除非您通过准备好的语句准备您的值;或者您确定数据库模式使用整数类型) .

在整数周围放置单引号同样有效,因此用单引号将任何值括起来可能是安全的,如下所示:

$result = $usdb->query(
    Database::INSERT, 
    "INSERT INTO users (id, `password`, group_id , active, created, updated) 
        VALUES (
            '{$user['id']}', 
            '{$user['password']}', 
            '{$user['group_id']}', 
            '{$user['active']}', 
            '{$user['created']}', 
            '{$user['updated']}'
        )
    "
);

注意事项:

您应该始终使用参数化查询(准备好的语句)。将原始 PHP 变量注入(inject) SQL 查询是极其不安全的。如果你有一个带有单引号的变量,它会破坏你的 SQL 语句的逻辑。

您可以在 the PHP manual 中阅读有关准备好的语句的更多信息.

那么您的 SQL 真正应该是这样的:

$sql = "
    INSERT INTO users (id, `password`, group_id , active, created, updated) 
    VALUES (
        :id, 
        :password, 
        :group_id, 
        :active, 
        :created, 
        :updated
    )
";

然后将您的实际值绑定(bind)到准备好的语句中。

关于PHP MYSQL 插入数据时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36875039/

相关文章:

php - 尝试调用 SendGrid API 时出现 "Unsupported SSL protocol version"

mysql - 如何在 Laravel 中导出 PDF 文件

php - 不正确的 PHP 时间 - 45 年前的 echo

javascript - 提交后项目选择消失

php - MySQL 仅回显一个元素

mysql - 从mysql导入数据

php - 当另一个表保存特定值时,如何使用 MySQL 将某些内容插入到表中

php - 直接在同一页面php更新

PHP stmt prepare失败,但是没有错误

php - 如何在我的查询 CODEIGNITER 中使用 DISTINCT