2

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.

3 Answers 3

0

try this:

<?php

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

echo $numRows;

?>
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your reply, but I'm afraid this does not fix the issue - it still returns blank/empty.
First check whether query is working. If yes then try another wordpress functions to execute it. I think query is perfect one.Have you checked this ???
Yes I have, and it was my mistake - I did not take out the , ARRAY_A argument when I changed the function, I tried it and it works! Thank you!
Welcome .....! Always take care of code that you paste from elsewhere.... Enjoy ........
0

Try this:

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

Comments

0

try this one

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

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

thanks.

1 Comment

It is different, i have used $total[0]['cnt'] instead of your's $total[0]['total']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.