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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.