Is mysql_num_rows effective and / or standard practice?

Some time ago, I was digging up SQLite, trying to migrate some of my sites to use it instead of MySQL. I hung up on the lack of a function to count the results, such as PHP mysql_num_rows(). After a short search, I found this mailing list , which, as I understand it, says that SQLite does not have this functionality because it is inefficient. It says this is a bad form for writing code that needs to know how many lines are returned.

I usually use mysql_num_rowsan empty return to check the results. For example:

$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);

if (mysql_num_rows($results)) {
    while ($row = mysql_fetch_array($results)) {
        echo "<p>$row[whatever]</p>";
    }
} else {
    echo "<p>No results found</p>";
}

The furious aversion to concept mysql_num_rows()in the SQLite community makes me wonder how terribly effective it is for regular MySQL in PHP.

Is there a better, more acceptable way to check the size of the MySQL result set in PHP other than mysql_num_rows()?

EDIT: I don't just use mysql_num_rowsto get a counter. I would use a query for this COUNT. I use it to check if there are any results before outputting everything. This is useful for something like displaying search results - it does not always guarantee that there will be results. In the SQLite world, I have to send one query COUNT, check if there is something, and then send a query SELECTto get everything.

+3
3

-, , mysql_fetch_array(). false, ( php.net).

$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);
if($results) {
    $row = mysql_fetch_array($results);
    if($row) {
        do {
            echo "<p>{$row[whatever]}</p>";
        } while($row = mysql_fetch_array($results));
    } else {
        echo "<p>No results found</p>";
    }

} else {
    echo "<p>There was an error executing this query.</p>";
}
+10

, , SELECT ed, . , , . , , , . , COUNT (*). COUNT (*), SELECT, .

, COUNT. . ( SQLite).

API- SQLite. , , .

0

As explained on the mailing list you found. It is inefficient to return the number of rows, because you need to allocate a lot of memory to store the entire (remaining) result set. What you can do is simply use a boolean to check if you output something.

$query = "SELECT * FROM table WHERE thing = 'whatever'";
$results = mysql_query($query);

$empty_result = true;
while ($row = mysql_fetch_array($results)) {
    echo "<p>$row[whatever]</p>";
    $empty_result = false;
}

if ($empty_result) {
    echo "<p>No results found</p>";
}
0
source

Source: https://habr.com/ru/post/1713232/


All Articles