Jump to content
Larry Ullman's Book Forums

Using Only Certain Information Returned By A Query


Recommended Posts

Here's what I'm trying do.

 

Let's say my database has 30 entries in it. I want to display the first 15 in one section of my page and the remaining 15 in a different section. So, I figured I would use mysql_affected_rows() to see how many entries were being returned. This works fine, but now I'm stuck on how exactly to write an if/while loop that loops through and prints out only the first half or the second half.

 

Or should I be going about it completely differently and simply writing a query that only returns the first or second half?

 

Any advice or direction would be greatly appreciated! Thanks.

Link to comment
Share on other sites

Several ways to do this. I would add result to an array and use for-loops to get half in each section.

 

Btw. With this example, I pretend you have rows called "id" and "name" in your DB. You just switch that to what you use.

 

// Add result to a new array called $rows
while ( $row = mysqli_fetch_array($result, MYSQL_ASSOC) )
{
$rows[] = $row;
}

$size = count($rows); // Get size of rows array
$half = floor($size / 2); // Get half the row size, round down

// Get first section
for ( $i = 0; $i < $half; $i++ )
{
echo $rows[$i]['id'] . ' '. $rows[$i]['name'];
}

// Get second section
for ( $i = $half; $i < $size; $i++)
{
echo $rows[$i]['id'] . ' '. $rows[$i]['name'];
}

 

You might need to change the last loop to $i <= $size. If one row gets dropped, do that.

 

Remember that this way would give you 50 rows in each section if 100 rows are returned. You need to use LIMIT in your queries or something like that.

  • Upvote 1
Link to comment
Share on other sites

First, you'd use mysqli_num_rows() not mysqli_affected_rows() to see the number of results in a SELECT query. Second, if it's the same page, instead of using an array, you could just use two FOR loops without ever using the WHILE. FOR loops aren't often used for database queries, but you can do it.

Link to comment
Share on other sites

 Share

×
×
  • Create New...