在mysql / php中插入错误

时间:2012-05-11 11:52:14

标签: php mysql

我有这个功能:

   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行的''附近使用正确的语法

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

5 个答案:

答案 0 :(得分:3)

您错过了)子句中的结束VALUES (。通常,在将SQL传递给mysql_query之前,更容易将SQL分配给变量(可以输出这样的调试用途)。

答案 1 :(得分: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,
));

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

答案 2 :(得分: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

答案 3 :(得分: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。

答案 4 :(得分: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());