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

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

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀