How can I count the numbers of rows that a MySQL query returned?

后端 未结 11 1948
北海茫月
北海茫月 2020-11-28 04:51

How can I count the number of rows that a MySQL query returned?

11条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 05:24

    If you're fetching data using Wordpress, then you can access the number of rows returned using $wpdb->num_rows:

    $wpdb->get_results( $wpdb->prepare('select * from mytable where foo = %s', $searchstring));
    echo $wpdb->num_rows;
    

    If you want a specific count based on a mysql count query then you do this:

    $numrows = $wpdb->get_var($wpdb->prepare('SELECT COUNT(*) FROM mytable where foo = %s', $searchstring );
    echo $numrows;
    

    If you're running updates or deletes then the count of rows affected is returned directly from the function call:

    $numrowsaffected = $wpdb->query($wpdb->prepare(
       'update mytable set val=%s where myid = %d', $valuetoupdate, $myid));
    

    This applies also to $wpdb->update and $wpdb->delete.

提交回复
热议问题