简体   繁体   中英

Displaying result of mysql query

I have managed to use other questions on here in order to find the median result in my table, but now I am unsure of how to print this result.

This is my PHP:

$query = "SELECT x.price 
          FROM price_pints x, price_pints y 
          GROUP BY x.price 
          HAVING SUM(    
                       SIGN( 
                             1 - SIGN( y.price - x.price ) 
                           ) 
                    ) / COUNT( * ) > .5 
          LIMIT 1"; 

$result = mysql_query($query) or die(mysql_error());

// Print out result
while($row = mysql_fetch_array($result)){
echo "The average price of a pint ". $row['type']. " is £".$row['x.price(price)'];
echo "<br />";
}

The result shows up as 5 when I test the sql query in phpmyadmin, but it doesn't display when I echo the result.

Previously I calculated the avg and that was easy to print as:

echo "The average price of a pint ". $row['type']. " is £".$row['AVG(price)'];

Now I am stuck as how to change the .$row[price(price)] ^^^

As the comments suggest, consider moving to PDO or mySQLi, as all mysql_ commands are being deprecated.

Your PHP needs to read;

echo "The average price of a pint ". $row['type']. " is £".$row['price'];

However, I'm wondering what you expect to be returned in your Type column? As you're not selecting it above, and further you will only be returning one single value, and one type of course, even though you're calculating a Median over all prices.

At the very least, your SQL would be;

      SELECT x.price, x.type 
      FROM price_pints x, price_pints y 
      GROUP BY x.price 
      HAVING SUM(    
                   SIGN( 
                         1 - SIGN( y.price - x.price ) 
                       ) 
                ) / COUNT( * ) > .5 
      LIMIT 1

First off, you need to look into using mysqli or PDO to run your query, you're completely susceptible to sql injections using mysql_query and its depreciated anyhow, and will soon be removed. That being said if your query is working when run directly on your databse it should run from php.

Check to see how many rows you are returning

$numrows = mysql_num_rows($result)

Make sure you are referencing the proper columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM