I am thinking about the most efficient way to make a function that returns the number of rows I get on a certain query. I need to have a lot of variations of the query as I use it for a lot of statistics.(in the real version it is about 5 variables, not 2) Instead of posting my full code I created a small snippet that will point out what I'm trying to overcome. $conn is my PDO connection. the name of the table as well as the names of the fields are fixed.
function stackOverflowDemo($var1,$var2){
global $conn;
$totalrows = $conn->query("select count(*) from $table WHERE firstfield = $var1 AND secondfield = $var2 ")->fetchColumn();
return $totalrows;
}
$output = stackOverflowDemo('1','30');
So right now it will give me the amount of rows who meet the above conditions. (firstfield = 1 AND secondfield = 30
) but now comes the clue : now I want the number of rows where firstfield is 1 and secondfield is anything
(like *). How can I make that work for me , without having to write a new function or a dedicated query ?
function stackOverflowDemo($var1,$var2){
global $conn;
$query = "select count(*) from $table WHERE firstfield IS $var1 AND secondfield IS $var2";
$totalrows = $conn->query($query)->fetchColumn();
return $totalrows;
}
$output = stackOverflowDemo('1','NOT NULL');
maybe this works for you?
now I want the number of rows where
firstfield
is1
andsecondfield
is anything (like *)
Your query should find occurrences of each firstfield
and secondfield
separately and then count them.
Omitting null
entries for secondfield
, you can try the following:
select
sum(firstfield) first_field_count
, sum(secondfield) second_field_count
from (
select
case when firstfield=1 then 1 else 0 end as firstfield
, case when secondfield is not null then 1 else 0 end as secondfield
from table_name
) t;