0

我有这个功能:

   public static function insert_user($user)
{
    $con = mysql_connect("localhost","root","") or die(mysql_error());
    mysql_select_db("speakom",$con) or die(mysql_error());
    mysql_query("INSERT INTO user (user_ip,user_name,full_name,email_address,password,gender,birthday,banned,role,country) 
        VALUES('".$user->ip."','".$user->name."','".$user->full_name."','".$user->email."','".$user->password."',".$user->gender.",'".$user->birthday."',".$user->banned.",".$user->role.",'".$user->country."'") or die(mysql_error());
    mysql_close($con);
}

我得到这个错误:

您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 2 行的 '' 附近使用正确的语法

错误指向哪里?我怎么知道错误在哪里?

4

5 回答 5

3

您缺少)VALUES (子句的结尾。通常,在将 SQL 传递给mysql_query.

于 2012-05-11T11:54:49.807 回答
2

不要大喊大叫,您应该使用 PDO 和准备好的语句,这是 PDO 风格的答案:

$con = new PDO('mysql:host=localhost;dbname=speakom', 'root', ''); // optionally add encoding options
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // enable exception throwing
$stmt = $db->prepare('INSERT INTO user (user_ip, user_name, full_name, email_address, password, gender, birthday, banned, role, country) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
$stmt->execute(array(
    $user->ip, $user->name, $user->full_name, $user->email, $user->password, 
    $user->gender, $user->birthday, $user->banned, $user->role, $user->country,
));

免责声明没有对此进行测试,但它应该给你一个好主意:)

于 2012-05-11T12:03:09.273 回答
1

你会跑吗

echo "INSERT INTO user (user_ip,user_name,full_name,email_address,password,gender,birthday,banned,role,country)      VALUES('".$user->ip."','".$user->name."','".$user->full_name."','".$user->email."','".$user->password."',".$user->gender.",'".$user->birthday."',".$user->banned.",".$user->role.",'".$user->country."'";

我建议你使用 `user` 而不是user

于 2012-05-11T11:55:43.030 回答
1
VALUES('".$user->ip."','".$user->name."','".$user->full_name."','".$user->email."','".$user->password."',".$user->gender.",'".$user->birthday."',".$user->banned.",".$user->role.",'".$user->country."'"

)最后不见了。顺便说一句,使用 PDO 或 mysqli。

于 2012-05-11T11:56:34.107 回答
1

您要插入的某些值不在引号中,并且您错过)VALUES. 尝试这个

mysql_query("INSERT INTO user (user_ip,user_name,full_name,email_address,password,gender,birthday,banned,role,country) 
    VALUES('$user->ip', '$user->name','$user->full_name', '$user->email', '$user->password', '$user->gender', '$user->birthday', '$user->banned', '$user->role', '$user->country')") or die(mysql_error());
于 2012-05-11T11:56:39.443 回答