To get half of MySQL table records here is what I’m using:
$numRows=mysql_num_rows(mysql_query("SELECT * FROM cultures"));
$half = $numRows/2;
Then on each side of the page, I limit the number of records by the half of it, and on the other side I order by DESC instead to get the other half:
$result = mysql_query("SELECT * FROM cultures ORDER BY name ASC LIMIT ".$half);
while($row = mysql_fetch_array($result)) {
$url = "artists.php?culture=".ucfirst($row['name']);
echo '<div class="homepage_culture_item">
<a href="'.$url.'"></a>
<img src="/images/flags/'.$row['name'].'.png" style="width: 30px; vertical-align: middle; margin-right: 10px;" />'.$row['name'].'
</div>
<br />';
}
Which works great, as you can see in this screenshot:

However, if there is an odd number of records in the table, I get an error:

Warning: mysql_fetch_array() expects parameter 1 to be resource,
boolean given in C:\wamp\www\index.php on line 50
It works great when there’s an even number of records but if another one is added, instead of just putting it on one side, it messes up because it is probably returning an error because when you divide 15 by 2, it will be a decimal and MySQL LIMIT can’t accept decimals (obviously). Is there a better way to do what I’m trying to do?
Thanks in advance!
You can just round it down so you always get an integer. That way, a decimal won’t break the query.
You’ll want to use a new
$halfvalue usingceil()on the other side to round up, so you don’t skip a row in the middle.As an aside, it might be better to do just one query returning every row, then output the rows up to
$halfon one side, then continue from that point to the end for the other side. Then you’re only hitting the database once and it’s easier to see what’s going on.e.g