简体   繁体   English

使用新的pdo方法将信息插入数据库会给我一个错误

[英]Inserting information into database using the new pdo method giving me an error

I am trying to migrate from the old SQL method to the new PDO methods for dealing with database. 我正在尝试从旧的SQL方法迁移到新的PDO方法来处理数据库。

Here is what I have so far: 这是我到目前为止的内容:

try{
$conn = new PDO(.......)//this code is working fine
$conn->exec("SET CHARACTER SET utf8");

$query = "INSERT INTO TABLE(name,username,password)VALUES(:name,:username,:password)";

$prepare_query = $conn->prepare($query);

$prepare_query->bindValue(':name',$name,PDO::PARAM_STR);
$prepare_query->bindValue(':username',$user,PDO::PARAM_STR);
$prepare_query->bindValue(':password',$pass,PDO::PARAM_STR);

$count = $conn->exec($prepare_query);//error is somewhere here
}catch(PDOException $e){
echo $e->getMessage();
}

if($count > 0) echo "done";

Now the error I am receiving is Warning: PDO::exec() expects parameter 1 to be string, object given in C:\\xampp\\htdocs\\drug_center\\includes\\NewAccount.php on line 42. 现在我收到的错误是警告:PDO :: exec()期望参数1为字符串,第42行的C:\\ xampp \\ htdocs \\ drug_center \\ includes \\ NewAccount.php中给出的对象。

I am a NEWBEE when it comes to the PDO methods. 关于PDO方法,我是NEWBEE。 I have read this ! 我已经读过 but here it is not showing me how to prepare the statement. 但是这里并没有告诉我如何准备声明。 I want to protect my data base as much as possible. 我想尽可能地保护我的数据库。 Can someone please explain where I have gone wrong and how to fix this? 有人可以解释我哪里出了问题以及如何解决吗?

The connection object's ->exec() method expects a string as its first argument containing the query to run, but the prepared statement does what you expect with ->execute() : 连接对象的->exec()方法期望一个字符串作为包含要运行的查询的第一个参数,但是准备好的语句使用->execute()可以达到您的期望:

$success = $prepare_query->execute();
// $success is true if execution was okay
$count = $prepare_query->rowCount();
// $count is the rows affected

Try binding in the exec method. 尝试在exec方法中进行绑定。

$sql = "INSERT INTO TABLE(name,username,password)VALUES(:name,:username,:password)";
$q = $conn->prepare($sql);
$q->execute(array(':name'=>$name,
                  ':username'=>$username,
                      ':password'=>$password));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM