Jump to content

COUNT in a given sequence


RON_ron

Recommended Posts

How can I get the count value in a sequence? (first count AZ then MI then WD tec...) and then echo it in the same seuence. Please help. This is what I've done so far.

 

$SomeVar = "AZ";
$query1 = "SELECT statez, COUNT(statez) AS Tstate FROM  distributors WHERE statez = '".$SomeVar."'";
$results1 = mysql_query($query1);

$SomeVar = "MI";
$query2 = "SELECT statez, COUNT(statez) AS Tstate FROM  distributors WHERE statez = '".$SomeVar."'";
$results2 = mysql_query($query2);

$SomeVar = "WD";
$query3 = "SELECT statez, COUNT(statez) AS Tstate FROM  distributors WHERE statez = '".$SomeVar."'";
$results3 = mysql_query($query3);

$values = array();  

while($line = mysql_fetch_array($results))
{
    $values[] = $line;
}

echo $values[0]['Tstate'].",,";
echo $values[1]['Tstate'].",,";
echo $values[2]['Tstate'].",,";
echo $values[3]['Tstate'].",,";
mysql_close($link);
?>

Link to comment
https://forums.phpfreaks.com/topic/213454-count-in-a-given-sequence/
Share on other sites

Hi

 

You basic idea should have displayed them in the right order (although there are a fair few other errors and it would be inefficient).

 

This will do it a bit more efficiently:-

 

<?php

$SomeVar = array("AZ","MI","WD");
$query = "SELECT statez, COUNT(statez) AS Tstate FROM  distributors WHERE statez = ('".implode("','",$SomeVar)."') GROUP BY statez, ORDER BY statez";
$results = mysql_query($query);

$values = array();  

while($line = mysql_fetch_array($results))
{
    $values[] = $line;
}

foreach($values AS $thisValue)
{
echo $thisValue['Tstate'].",,";
}

mysql_close($link);
?>

 

This assumes you want the data in an array before outputting it, and that the order you want is alphabetic. If you just want to output it:-

 

<?php

$SomeVar = array("AZ","MI","WD");
$query = "SELECT statez, COUNT(statez) AS Tstate FROM  distributors WHERE statez = ('".implode("','",$SomeVar)."') GROUP BY statez, ORDER BY statez";
$results = mysql_query($query);

while($line = mysql_fetch_array($results))
{
    echo $line['Tstate'].",,";
}

mysql_close($link);
?>

 

All the best

 

Keith

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.