Hello. Interested in a 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 (): we don't have a valid MySQL result resource ..." so no?

  • Starting with the fact that it swears at mysql_fetch_rows, whom I do not observe here and which relates to the ternary a little less than nothing ... = D - Alexey Sonkin
  • no, it is him who swears. is syntactically correct? for ($ i = 1; $ i <($ qnum <10? 1: $ qnum / 10); $ i ++) - tfiwsrets
  • I don’t see Mysql in focus ... Syntactically, that’s right, but I don’t understand what you wanted to achieve with this line = 3 - Alexey Sonkin
  • the function creates links like 1, 2, 3 ... on each page there are 10 entries. those. if there are 11 records, a link 2 is created. in order to find out whether a link should be created, I will find out how many rows in the database there are. if there are less than 10, then it is not necessary to create anything and a cycle. if more, then divide the number of records by 10 and create a link 2. something like that. ) clumsy? - tfiwsrets
  • Here you can get by with a simple mathematical expression that will give the same result =) - Alexey Sonkin

1 answer 1

I have not written in PHP for a long time, but as far as I remember - correctly. 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 millions in your guest records - thanks to the spamboot. Maybe it is worth then at the level of the SQL query to choose the amount of "no more than"? For example, the following vsevdo-SQL code:

 SELECT * FROM guestbook WHERE (какое-то условие) ORDER BY timestamp DESC LIMIT 10 OFFSET 10*(page-1) 

where page is the current page number.

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

Another small tip: use the most recent MySQL access library, or even better - use ORM.