Alternative for mysql_num_rows using PDO

后端 未结 5 1950
逝去的感伤
逝去的感伤 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');
    

提交回复
热议问题