Alternative for mysql_num_rows using PDO

后端 未结 5 1925
逝去的感伤
逝去的感伤 2020-11-27 18:41

Right now I have a PHP file that does a MYSQL query and then counts rows like this:

$count=mysql_num_rows($result);


if ($count == 1) {
    $message = array         


        
相关标签:
5条回答
  • 2020-11-27 18:53
    $res = $DB->query('SELECT COUNT(*) FROM table');
    $num_rows = $res->fetchColumn();
    

    or

    $res = $DB->prepare('SELECT COUNT(*) FROM table');
    $res->execute();
    $num_rows = $res->fetchColumn();
    

    You can use this to ask if data exists or is selected, too:

    $res = $DB->query('SELECT COUNT(*) FROM table');
    $data_exists = ($res->fetchColumn() > 0) ? true : false;
    

    Or with your variables:

    $res = $DB->query('SELECT COUNT(*) FROM table');
    $message = ($res->fetchColumn() > 0) ? array('status' => 'ok') : array('status' => 'error');
    
    0 讨论(0)
  • 2020-11-27 18:55
    $stmt = $db->query('SELECT * FROM table');  
    $row_count = $stmt->rowCount();  
    echo $row_count.' rows selected';
    
    0 讨论(0)
  • 2020-11-27 18:55

    Maybe you can use PDO's "fetchAll" method, which returns an array containing all the SELECT results. Then use "count" method to count the array's rows.

    Ex:

    $rows = $stmt->fetchAll();
    $num_rows = count($rows);
    
    0 讨论(0)
  • 2020-11-27 19:03

    Can be like that...

    $numRows = $conn->query("SELECT COUNT(*) FROM yourtable")->fetchColumn();
    echo $numRows; 
    
    0 讨论(0)
  • 2020-11-27 19:15

    If you are not using prepared statements then try:

    $find = $dbh->query('SELECT count(*) from table');
    if ($find->fetchColumn() > 0){
        echo 'found';
    }
    

    However, if you choose prepared statements, which i highly recommend, then:

    $find = $dbh->prepare('SELECT count(*) from table');
    $find->execute();
    if ($find->fetchColumn() > 0){
        echo 'found';
    }
    
    0 讨论(0)
提交回复
热议问题