Jump to content

Loop Logic?


Solarpitch

Recommended Posts

Hey guys,

 

I have the below script to count the number of values in a table. The problem is I need to run the query 11 times with a different "type" each time but obviously dont want to repeat the function 11 times due to performance issues. I know it can be done using a loop but I am having problems trying to get my head around it.

 

Heres the script...

 


<?php

function count_types($area)
{
dbconnect();

        $num_rows = array()

$sql = "select count(*) from property_info where location=".$area." and type = 1";

$result = mysql_query($sql);
$query_data = mysql_fetch_row($result);
$num_rows[0] = $query_data[0];

return $num_rows;

}

?>

 

So basically I need to return the $num_rows array with...

 

$num_rows[0] assigned value type 1

$num_rows[1] assigned value type 2

$num_rows[2] assigned value type 3

$num_rows[3] assigned value type 4

 

and so on....

Link to comment
https://forums.phpfreaks.com/topic/102496-loop-logic/
Share on other sites

Try something like this:

 

<?php
function count_types($area,$types){
    $num_rows = array();
    $sql = "SELECT COUNT(*),type FROM property_info WHERE location='$area' AND type IN(".implode($types).") GROUP BY type";
    $result = mysql_query($sql) or die(mysql_error());
    while(list($count,$type) = mysql_fetch_row($result)){
        $num_rows[$type] = $count;
    }
    return $num_rows;
}
$area = 'Some area';
$types = array(1,2,3,4);//specify the types in an array. If you're wanting ALL types in your query, delete this, delete the parameter and remove the AND type IN(...) part of the WHERE clause from the query.
echo '<pre>'.count_types($area,$types).'</pre>';
?>

Link to comment
https://forums.phpfreaks.com/topic/102496-loop-logic/#findComment-524855
Share on other sites

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.