1

我正在尝试执行一个注册类。但是查询不起作用(查询被突出显示。这似乎是一个简单的问题,但我没有看到它。我回显查询并通过 phpmyadmin sql 查询框复制并执行它,它显示错误 1064。我似乎找不到任何问题。

    <?php
class register
{
    protected $username;
    protected $password;
    protected $email;
    protected $postcode;

    public function __construct()
    {   
    }

    public function insertuser($username, $password,$email, $postcode)
    {
        $this->_email = mysql_real_escape_string($email);
        $this->_password = mysql_real_escape_string($password);
        $this->_username = mysql_real_escape_string($username);
        $this->_postcode = mysql_real_escape_string($postcode);



    **$query = "INSERT INTO 'users'('user_id', 'username', 'password', 'email', 'postcode') VALUES  (NULL,'{$username}','{$password}','{$email}','{$postcode}');";**


        echo $query;
        $result = mysql_query($query);
        return $result;
    }


}
?>
4

4 回答 4

1

error 1064表示 SQL 语法错误。您在表名和列名周围使用了单引号:'. 用反引号替换它们:`

"INSERT INTO `users` (
  `user_id`, `username`, `password`, `email`, `postcode`
) VALUES  (
   NULL,'{$username}','{$password}','{$email}','{$postcode}'
);"

进一步注意,您不应该使用 mysql 扩展编写新代码。PHP 开发人员已将其标记为已弃用。请改用PDOmysqli

于 2013-04-30T21:29:27.403 回答
0

The syntax seems to be wrong. Table and column names should not have quotes around them. They should have backticks or nothing. Otherwise they are treated as string literals.

INSERT INTO users (user_id, username, password, email, postcode)
VALUES  (NULL,'{$username}','{$password}','{$email}','{$postcode}')

You also don't need the field list if the values list is complete and in order. The ending semicolon is undesirable (though ineffective).


Your code is vulnerable to injection. You should use properly parameterized queries with PDO or mysqli

于 2013-04-30T21:30:10.750 回答
0

You have single quotes around your table and columns. You are confusing these with backticks - which are unnecessary unless you have used a reserved word (which you should avoid IMO).

Also, you were not using your sanitized variables and therefore vulnerable to SQL injection.

INSERT INTO users (user_id, username, password, email, postcode) VALUES (NULL,'{$this->_username}','{$this->_password}','{$this->_email}','{$this->_postcode}');

Obligatory: The mysql_* functions will be deprecated in PHP 5.5. It is not recommended for writing new code as it will be removed in the future. Instead, either the MySQLi or PDO and be a better PHP Developer.

于 2013-04-30T21:30:32.110 回答
0

除了使用准备好的语句之外,您绝对应该考虑切换到 mysqli。使用准备好的语句将使您的查询更容易,并进一步保护您免受注入。

http://php.net/manual/en/mysqli.prepare.php

至于你的错误,有几件事是错误的。不要使用引号调用数据库。不要用引号处理表名。这些都是爆丸所指出的。

最后,我看不到您在哪里打开了 mysqli 连接。

于 2013-04-30T22:03:47.267 回答