2

I am trying to migrate from the old SQL method to the new PDO methods for dealing with database.

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.

I am a NEWBEE when it comes to the PDO methods. 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?

4

2 回答 2

4

连接对象的->exec()方法需要一个字符串作为它的第一个参数,其中包含要运行的查询,但是准备好的语句可以满足您的期望->execute()

$success = $prepare_query->execute();
// $success is true if execution was okay
$count = $prepare_query->rowCount();
// $count is the rows affected
于 2013-04-22T16:22:27.970 回答
0

尝试在 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));
于 2013-04-22T16:28:52.437 回答