如果在PDO预处理语句中插入成功,则为if / else语句的语法 [英] Syntax for if/else statement if insert was successful in a PDO prepared statement

查看:213
本文介绍了如果在PDO预处理语句中插入成功,则为if / else语句的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从mySql语句切换到PDO预处理语句,但是我很难找到if / else语句的正确语法,如果插入成功,我必须使用它(之前是 if($ result){...} )。

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) {...}).

我知道$ stmt-> execute();成功时返回true,失败时返回false,但我无法确定如何设置语句以对其执行操作。

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.

新代码(PDO预备声明)

$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();
}

这是原始的其余部分if($ gender ===female) function

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();
    }   

我删除了大部分变量以简化操作(因为代码相同)

推荐答案

有很多方法可以检查INSERT是否有效正确。

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

如你所说, $ stmt-> execute(); 成功时返回true,失败时返回false。所以你可以使用:

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

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

PDO执行文档

rowCount将返回查询所包含的行数。插入成功后,该值应为1.

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文档

如果您的表有一个ID列,您可以使用 lastInsertId()

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) {...}

注意:您必须致电<$ PDO对象上的c $ c> lastInsertId ,而不是 $ stmt

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

PDO lastInsertId文档

这篇关于如果在PDO预处理语句中插入成功,则为if / else语句的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆