Checking if mysql_query returned anything or not

前端 未结 5 2127
天命终不由人
天命终不由人 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: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
    }
    

提交回复
热议问题