I want the highest and the lowest value of a table, why can't I save that value in PHP?

32 views Asked by At
$category = htmlspecialchars($_GET['category']);

$sql = "(SELECT number 
        FROM german 
        WHERE german.category_german LIKE ".$category." 
        ORDER BY number DESC 
        LIMIT 1) as 'high', 
        (SELECT number 
        FROM german 
        WHERE german.category_german LIKE ".$category." 
        ORDER BY number ASC 
        LIMIT 1) as 'low'";
    if ($result = $conn -> query($sql)) {
      while ($row = $result -> fetch_row()) {
        
          $high_value = $row[high];
          $low_value = $row[low];
          $r_n = rand($low_value,$high_value).PHP_EOL;
          echo $r_n;
          }

      }

What am I missing? I want the highest and the lowest value of a table, why can't I save that value in PHP? I just can't access the values. And I tried out MIN and MAX as well, but they didn't function neither:

$category = htmlspecialchars($_GET['category']);

$sql = "SELECT MIN('number') AS 'low', MAX('number') AS 'high' FROM german WHERE german.category_german LIKE ".$category."";
    if ($result = $conn -> query($sql)) {
      while ($row = $result -> fetch_row()) {
          $high_value = $row[high];
          $low_value = $row[low];
          $r_n = rand($low_value,$high_value).PHP_EOL;
          echo $r_n;
          }

      }

As a result of $r_n I only get 0. The database shouldn't be the problem. Beforehand (where I only used the highest value) everything functioned:

$category = htmlspecialchars($_GET['category']);

$sql = "SELECT number FROM german WHERE german.category_german LIKE ".$category." ORDER BY number DESC LIMIT 1";
if ($result = $conn -> query($sql)) {
  while ($row = $result -> fetch_row()) {
    
      $r_n = $row[0];
      $r_n = rand(1,$r_n).PHP_EOL;
      echo $r_n;
      }

  }
1

There are 1 answers

6
Barmar On

You can't use multiple SELECT statements at top-level of a query. They would have to be subqueries:

SELECT (SELECT ...) AS high, (SELECT ...) AS low

Your second query would have worked, but you shouldn't have quotes around number. That makes it a literal string, not the column values. So MAX('number') should be MAX(number), MIN('number') should be MIN(number). See When to use single quotes, double quotes, and backticks in MySQL

And if category is a string, you need to put quotes around $category:

WHERE german.category_german LIKE '".$category."'"

But the better way to resolve that problem is to use a prepared statement with parameters, How can I prevent SQL injection in PHP? than substituting variables directly into the query. See