Pepe
Pepe

Reputation: 1002

Count table rows with special "keyword" (SQL)

I have a SQL-table called "usermeta", inside this table are lots of columns and rows. I need the column "meta_key" and want to count the rows with the keyword "Users".

Whats wrong with my script?

<?php
$user_count = $wpdb->get_var( "SELECT COUNT(meta_key) AS Users FROM $wpdb->usermeta" );
echo "<p>Users count: {$user_count}</p>";
?>

Upvotes: 0

Views: 47

Answers (2)

DhruvJoshi
DhruvJoshi

Reputation: 17126

SQL query should be

SELECT COUNT(DISTINCT meta_key) FROM  usermeta WHERE meta_key LIKE '%Users%'

and since we did not want unique results

I always get "1" - does it only counts this entry once? – Pepe

and code should be therefore

<?php
$user_count = $wpdb->get_var( "SELECT COUNT(meta_key) AS Users FROM $wpdb->usermeta WHERE meta_key like '%Users%'" );
echo "<p>Users count: {$user_count}</p>";
?>

Upvotes: 1

Randrian
Randrian

Reputation: 1085

You should probably use a WHERE clause to filter for rows with have your keyword. For a detailed answer you should explain more one how your table actually looks like.

Upvotes: 0

Related Questions