2016-01-22 162 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();