dongque3797 2012-12-12 05:40
浏览 117
已采纳

如果在PDO预处理语句中插入成功,则为if / else语句的语法

I'm trying to switch from mySql statements to PDO prepared statements, but I'm having trouble figuring out the correct syntax for the if/else statements that I have to use if the insert was successful (which were previously if($result) {...}).

I know that $stmt->execute(); returns true on success or false on failure, but I haven't been able to determine how to set the statement up to act on that.

The new code (PDO prepared statement)

$gender = $_POST['gender'];  
if ($gender==="female" ) {
try {      
   $stmt = $conn->prepare('INSERT INTO customer_info (fname...) VALUES(:fname...)');
   $stmt->bindParam(':fname', $_POST['fname'], PDO::PARAM_STR);
   $stmt->execute();   
    } catch(PDOException $e) {
  echo $e->getMessage();
}

This is the rest of the original if ($gender==="female") function

$result = @mysql_query($qry);    
    if($result) {          
      $qry="SELECT * FROM customer_info WHERE user_name='$_POST['user_name']' AND password='$_POST['password']'";
      $result=mysql_query($qry);          
if($result) {
    if(mysql_num_rows($result) == 1) {
        //user_name Successful
        session_regenerate_id();
        $member = mysql_fetch_assoc($result);
        $_SESSION['SESS_USER_ID'] = $member['user_id'];
        session_write_close();
        header("location: flatter_iframe.html");
        exit();
    }else {        
        header("location: login_failed.html");
        exit();
    }   

I've deleted most of the variables in order to simplify things (since the code is the same)

  • 写回答

1条回答 默认 最新

  • dongpangbu4016 2012-12-12 11:39
    关注

    There are a number of ways you can check whether an INSERT worked correctly.

    1. Return value from $stmt->execute()

    As you said, $stmt->execute(); returns true on success or false on failure. So you can use:

    $result = $stmt->execute();
    if ($result) {...}
    

    PDO Execute documentation here

    2. Row Count

    rowCount will return the number of rows afffected by a query. After a successful insert, this should be 1.

    $stmt->execute();
    $affected_rows = $stmt->rowCount();
    if ($affected_rows == 1) {...} 
    

    PDO rowCount documentation here

    3. Last Inserted Id

    If your table has an ID column, you can return the ID of the last inserted row using lastInsertId().

    $stmt->execute();
    $newCustomerInfoId = $pdo->lastInsertId();
    if ($newCustomerInfoId) {...}
    

    Note: You must call lastInsertId on the PDO object, not the $stmt.

    PDO lastInsertId documentation here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波