Question

Trying to find the median for an array in a MYSQL database.

Currently, I am grabbing my data like so:

$middleMonth = "SELECT Day, COUNT(Day) AS totalNumber FROM finalbaby GROUP BY Day ORDER BY COUNT(Day) DESC LIMIT 1, 300";
$middleResult = mysql_query($middleMonth);

I am then putting it into an array like so.

$names=array();
while($row = mysql_fetch_assoc($middleResult)) {
$names[] = $row['Day'];

I am then trying to find the median of that array:

            sort($names);
            $count = count($names);
            $middleval = floor(($count-1)/2); 
                if($count % 2) { 
                    $median = $names[$middleval];
                } else { 
                    $low = $names[$middleval];
                    $high = $names[$middleval+1];
                    $median = (($low+$high)/2);
                }

        return $median;

        }

        var_dump($names);

I am not getting any errors, but it crashes my application.

Any suggestions on what I am doing wrong?

Was it helpful?

Solution

are you closing the while in your second code black before your third code block?

answered:

I close the while in my last }

Fail... close while in second code block before running code in third code block... this will find the median only once instead of trying to find the median every time you set a name from a mysql returned row. The first time, the count of names would be 1 and then you subtract 1 = 0 and divide by two. This will give you 0. Then you try to get the remainder of 0 and 2. This throws off the rest of your code. Try this:

$middleMonth = "SELECT Day, COUNT(Day) AS totalNumber FROM finalbaby GROUP BY Day ORDER BY COUNT(Day) DESC LIMIT 1, 300";
$middleResult = mysql_query($middleMonth);
$names=array();
while($row = mysql_fetch_assoc($middleResult)) {
    $names[] = $row['Day'];
}
sort($names);
$count = count($names);
$middleval = floor(($count-1)/2); 
if($count % 2) { 
    $median = $names[$middleval];
} else { 
    $low = $names[$middleval];
    $high = $names[$middleval+1];
    $median = (($low+$high)/2);
}
echo $median;
var_dump($names);

//previous code
//if this code is inside function then return if not then print
//return $median;
//if this code is inside function then the return above will cancel this var_dump
//var_dump($names);

Also please remember

Warning! This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top