Reputation: 117
I am keeping track of a few things on my site and im using a lot of queries because they need different conidtions
for example
$example = mysql_query("SELECT column FROM table WHERE column = 'Value1'");
$example_row = mysql_num_rows($example);
$example1 = mysql_query("SELECT column FROM table WHERE column = 'Value2'");
$example_row1 = mysql_num_rows($example1);
And so on, the value is always different so im having trouble finding a way to make this in to one query where i could still get different rows count for different values, is it possible?
I could test the row to see if it matches the value
if ($row == 'value'){
}
Multiple times but it still seems bad
Upvotes: 1
Views: 145
Reputation: 3204
I believe you want the count per value:
$values = ["value1", "value2", ...];
$query = "SELECT ";
for($i = 0; $i < count($values); $i++)
{
$query .= "SUM(IF(column = '$values[$i]')) AS v$i";
if($i != count($values) - 1)
$query .= ","; //Only add ',' if it's not the last value
$query .= " "; //We need the spaces at the end of every line
}
$query .= "FROM table";
//Let mysql do its work, run the query etc., store the resultset in $row;
Now you can dynamically iterate through the resultset:
$results = [];
for($i = 0; $i < count($values); $i++)
{
$string = "v"+ $i;
$results[] = $row[$string];
}
Upvotes: 0
Reputation: 219814
Use IN()
SELECT column FROM table WHERE column IN('Value1', 'Value2');
Upvotes: 2