Checking if mysql_query returned anything or not

前端 未结 5 2132
天命终不由人
天命终不由人 2021-02-18 16:56
$query = \"SELECT * FROM `table`\";
$results = mysql_query($query, $connection);

If \'table\' has no rows. whats the easiest way to check for this.?

相关标签:
5条回答
  • 2021-02-18 17:25

    You could use mysql_num_rows($results) to check if 0 rows were returned, or use this faster alternative:

    $query = "SELECT COUNT(*) AS total FROM table";
    $results = mysql_query($query, $connection);
    $values = mysql_fetch_assoc($results);
    $num_rows = $values['total'];
    
    0 讨论(0)
  • 2021-02-18 17:27

    Jeremy Ruten's answer above is good and executes quickly; on the other hand, it only gives you the number of rows and nothing else (if you want the result data, you have to query the database again). What I use:

    // only ask for the columns that interest you (SELECT * can slow down the query)
    $query = "SELECT some_column, some_other_column, yet_another_column FROM `table`";
    $results = mysql_query($query, $connection);
    $numResults = mysql_num_rows($results);
    if ($numResults > 0) {
       // there are some results, retrieve them normally (e.g. with mysql_fetch_assoc())
    } else {
       // no data from query, react accordingly
    }
    
    0 讨论(0)
  • 2021-02-18 17:28

    One thing i noticed that was missed was the fact that the query might not succeed, so you do need to check if the $results variable is set. I'll use the answer given by yjerem as an example.

    $query = "SELECT COUNT(*) AS total FROM table";
    $results = mysql_query($query, $connection);
    if ($results) { // or use isset($results)
    $values = mysql_fetch_assoc($results);
    $num_rows = $values['total'];
    }
    
    0 讨论(0)
  • 2021-02-18 17:31

    If you loop through the results, you can have a counter and check that.

    $x = 1;
    $query = mysql_query("SELECT * FROM table");
    while($row = mysql_fetch_assoc($query))
    {
      $x++;
    }
    if($x == 1)
    {
      //No rows
    }
    
    0 讨论(0)
  • 2021-02-18 17:33

    Alternatively you can simply check if the result of mysql_fetch_assoc is false.

    $query = "SELECT * FROM `table`";
    $results = mysql_query($query, $connection);
    $Row = mysql_fetch_assoc($results);
    if ($Row == false)
    {
      $Msg = 'Table is empty';
    }
    
    0 讨论(0)
提交回复
热议问题