2016-01-22 163 views
0

我正在使用pdo在php中插入一些数据到数据库中,我想确保一切正常吗? 例如我知道姓名和家庭插入表中?如何知道pdo中准备函数的返回值php

$query="INSERT INTO `table`(`name`, `family`) VALUES (:fname ,:lname)"; 
    $statement=$conncection->prepare($query); 
    $statement->bindParam(':fname',$_POST['name']); 
    $statement->bindParam(':lname',$_POST['family']); 
    $result=$statement->execute(); 

回答

0

您已经有了要在$ _POST数组中插入的名称和族。 你需要做的是首先检查post数组的值是否符合你的要求,然后在插入值之前使用try catch块,这样会更安全。

if(!empty($_POST['name']) && !empty($_POST['family'])) 
{ 
    try 
    { 
     $query="INSERT INTO `table`(`name`, `family`) VALUES (:fname ,:lname)"; 
     $statement=$conncection->prepare($query); 
     $statement->bindParam(':fname',$_POST['name']); 
     $statement->bindParam(':lname',$_POST['family']); 
     $statement->execute(); 
     $id=$connection->lastInsertId(); 

     //Use the ID if you need it here another query etc. 

    } 
    catch (PDOException $e) 
    { 
     //Write your code to handle the exception here 
    } 
} 
2

你会使用rowCount()UPDATEINSERTDELETE时获得受影响的行数。

$affectedRows = $result->rowCount();