douce1368 2015-10-03 12:34
浏览 68
已采纳

计算PDO准备语句中的行数

I have two questions regarding codes below.

  1. I know the second code is correct but not sure if first is also correct both do same thing first one is just easy to write.
  2. I want to count the number of rows in database for the selected element if ($query->num_rows == 1) { doesn't work so how to rowcount for the code below.

First code:

 $query = $db->prepare("SELECT * from users WHERE username = :username");
 $query->execute(array(':username'=>$un));

Second:

$result = "SELECT * from users WHERE username = :username";
$query = $db->prepare( $result ); 
$stmt->bindValue(':username'=>$un);
$query->execute($stmt);
  • 写回答

2条回答 默认 最新

  • dpo15099 2015-10-04 08:39
    关注

    First, if you want to ensure that only one username is selected, you can use LIMIT in your MySQL statement

    SELECT * from users WHERE username = :username ORDER BY id DESC LIMIT 1
    

    Or:

    SELECT DISTINCT(username) from users WHERE username = :username```
    

    Even better, when creating the table, you can require that the username is unique:

    CREATE TABLE users (
        id INT NOT NULL AUTO_INCREMENT,
        username VARCHAR(255) NOT NULL,
        ...
        PRIMARY KEY (id),
    );
    

    Second, to verify that a row was actually retrieved from the dabase, you can use fetch:

    $query = $db->prepare("SELECT * from users WHERE username = :username");
    $query->execute(array(':username'=>$un));
    $rows = $query->fetch(PDO::FETCH_NUM);
    if($rows[0]) { 
        // Row exists
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?