[英]Why won't this PDO code INSERT?
$sql = $db->prepare("INSERT INTO users (user_username, user_password, user_email) VALUES ($username, $password, $email)");
$sql->bindParam(':user_name', $username);
$sql->bindParam(':user_password', $password);
$sql->bindParam(':user_email', $email);
$sql->execute();
I'm trying to learn PDO rather than using mysql_ but I'm running into a problem. 我正在尝试学习PDO,而不是使用mysql_,但遇到了问题。 This doesn't seem to be inserting and I'm not sure why. 这似乎没有插入,我不确定为什么。
I'm not getting any error messages either so I don't know what to Google. 我也没有收到任何错误消息,所以我也不知道Google应该怎么做。
Also, is the $db variable being in an included file (config.php which has all the database details) a problem? 另外,包含文件(包含所有数据库详细信息的config.php)中的$ db变量是否有问题?
Try - 尝试-
$sql = $db->prepare("INSERT INTO users (user_username, user_password, user_email) VALUES (:user_name, :user_password, :user_email)");
$sql->bindParam(':user_name', $username);
$sql->bindParam(':user_password', $password);
$sql->bindParam(':user_email', $email);
$sql->execute();
Use :user_name, ...
in your $db->prepare()
not $username, ...
在$db->prepare()
使用:user_name, ...
而不是$username, ...
First thing's first, when you're developing turn on error reporting so you can see any error messages. 首先,在开发过程中,请打开错误报告,以便查看所有错误消息。
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
Executing the code you have should be producing some sort of error because you are trying to bind to parameters that don't exist. 执行代码将产生某种错误,因为您试图绑定到不存在的参数。 Named parameters need to start with a :
or if you would just prefer placeholder type parameters, you can use ?
命名参数需要先从一个:
或者如果你只是喜欢占位符类型的参数,你可以使用?
instead. 代替。 When you do: 当您这样做时:
...VALUES ($username, $password, $email)"
The variables will be parsed into their actual values: 变量将被解析为其实际值:
...VALUES (bob, $2y$14$youarehashingpasswordsright, bob@gmail.com)"
which of course, would be a syntax error in your SQL. 当然,这将是SQL中的语法错误。 Instead, you need to put their parameter names: 相反,您需要放置其参数名称:
......VALUES ( :username , :password , :email )"
Then if that doesn't work, look at any errors being produced and make sure the queries are actually being committed. 然后,如果这样不起作用,请查看正在产生的任何错误,并确保查询实际上已提交。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.