MySQL Returns PHP Associative Array – but I Can’t Access Array Data

I have two records in the MySQL table. I am trying to use SELECT COUNT(*) AS total FROM tableA but I am not getting the results I am expecting.

The code below will echo Array ( [0] => Array ( [cnt] => 2 ) ):

Read More
// Count the amount of records in the table
$total = $wpdb->get_results( "SELECT COUNT( * ) AS total FROM tableA", 'ARRAY_A' );

echo "Total Records:" . print_r( $total );

The code below echos nothing:

// Count the amount of records in the table
$total = $wpdb->get_results( "SELECT COUNT( * ) AS total FROM tableA", 'ARRAY_A' );

echo "Total Records:" . $total[0]['total'];

How can I simplify this? What am I doing wrong? I’m racking my brain over this and I just can’t get it to work.

Related posts

Leave a Reply

3 comments

  1. try this one

    $total = $wpdb->get_results( "SELECT COUNT( * ) AS total FROM tableA", 'ARRAY_A' );
    
    echo "Total Records:" . $total[0]['cnt'];
    

    thanks.

  2. Try this:

    $sql = "SELECT COUNT( * ) AS total FROM tableA";
    $sth = $DC->prepare($sql);
    $sth->execute();
    $result = $sth->fetch(PDO::FETCH_ASSOC);                
    echo $result['total'];