douduan5086 2011-12-27 03:36
浏览 38
已采纳

PDO准备语句:如何执行,检查受影响的行,然后获取字段

I'm very new to PDO - only being told to head in that direction this morning. So, hear me out. I'm trying to rewrite my login verification function from a standard mysql_query() to a PDO prepared statement, but I'm encountering some issues.

The function loginCheck() passes the supplied email and password, then grabs the salt from the matching email, if the number of affected rows of that query was 1, apply the variable $salt to the result of that query.

For the latter portion of the function, I was previously simply using:

// standard mysql query goes here

if (mysql_num_rows($query) == 1) {
    $salt = mysql_result($query, 0);
}

Now my entire function looks like:

// new mysql query below 

global $dbh;

$stmt = $dbh->prepare("SELECT `salt` FROM `users` WHERE `email`=? LIMIT 1");
$stmt->execute($email);

// not sure what to write here?

but I'm having trouble understanding how to translate the topmost portion of code to something similar in PDO. I'm also probably doing something else wrong here (as always), so point it out to me as well.

I've looked through the PHP manual and I simply cannot understand most of it. Any ideas?

  • 写回答

2条回答 默认 最新

  • dpl22899 2011-12-27 04:18
    关注

    I guess what you're looking for is PDOStatement::rowCount:

    $stmt = $dbh->prepare("SELECT `salt` FROM `users` WHERE `email`=? LIMIT 1");
    $stmt->execute($email);
    if ($stmt->rowCount() == 1) {
        $salt = $stmt->fetchColumn(0);
    }
    

    I'd rather write this like this though:

    $stmt = $dbh->prepare("SELECT `salt` FROM `users` WHERE `email`= :email LIMIT 1");
    $stmt->execute(compact('email'));
    
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($user) {
        // work with $user['salt']
    }
    

    Explicit naming is more robust than depending on column counts.


    To understand the manual, you need to understand object oriented notation/concepts. The documentation for the PDO class looks like:

    PDO {
       ...
       PDOStatement prepare ( string $statement [, array $driver_options = array() ] )
       ...
    }
    

    This means a PDO object ($dbh in your example), has a method prepare which returns a PDOStatement object. You're using it like this:

    $stmt = $dbh->prepare(...);
    

    So $stmt is a PDOStatement object. Knowing this you can look at the documentation for PDOStatement, and see that it has a method int PDOStatement::rowCount ( void ), which you can use.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

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