Mario.Hydrant
Mario.Hydrant

Reputation: 306

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 ) ):

// 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.

Upvotes: 2

Views: 391

Answers (3)

Krunal Shah
Krunal Shah

Reputation: 2101

try this one

$total = $wpdb->get_results( "SELECT COUNT( * ) AS total FROM tableA", 'ARRAY_A' );

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

thanks.

Upvotes: 1

Anand Solanki
Anand Solanki

Reputation: 3425

try this:

<?php

$numRows = $wpdb->get_var( "SELECT COUNT( * ) AS total FROM tableA");

echo $numRows;

?>

Upvotes: 0

DS.
DS.

Reputation: 2994

Try this:

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

Upvotes: 0

Related Questions