Ternary operator in PHP loop

Interested in the ternary operator in php. I wrote this function:

function links()
    if ($qname = mysql_query("SELECT * FROM guestbook"))
        $qnum = mysql_num_rows($qname);
        for ($i = 1; $i < ($qnum < 10 ? 1 : $qnum / 10) ; $i++)
             echo "<div class='links'>"."<a href='/testphp/guestbook/guestbook.php?id=".$i."'>".$i."</a>"."</div>";
     echo "<br />";

php swears “Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource…”
so you can’t?

Answer 1, authority 100%

I haven’t written in PHP for a long time, but as far as I remember, it’s correct. And the problem is somewhere else.

At the same time, let me look at your code from the other side;) Suppose you have a couple of million entries in your guestbook – thanks to the spambot. Maybe it’s worth then at the level of the SQL query to select the amount of “no more than”? For example, here is a pseudo-SQL code:

SELECT * FROM guestbook WHERE (- )
    ORDER BY timestamp DESC
    LIMIT 10
    OFFSET 10*(page-1)

where pageis the current page number.

To find out the total number of records, it is better to use a separate query, for example:
SELECT COUNT(id) FROM guestbook

Another little tip: use the latest MySQL access libraries, or even better, use an ORM.

Leave a reply

Please enter your comment!
Please enter your name here