Limit the database results?

Asked

Viewed 348 times

5

Continuing with the classroom videos, I came across a method of displaying database data a little different, in the video is used:

$result = mysqli_query($conn, 'SELECT * FROM comentarios ORDER BY data DESC');
$row = mysqli_fetch_assoc($result);
$totalRows = mysqli_num_rows($result);
// e depois um do while para repetir a impressão:
do
{
echo $row['coluna0'];
echo $row['coluna1'];
echo $row['coluna2'];
}while($row = mysqli_fetch_assoc($result));

But I had trouble implementing this code and I put the following:

echo '<table>';
 $result = mysqli_query($conn, 'SELECT * FROM comentarios ORDER BY data DESC');
 while (($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) != NULL)
 {
     echo "<tr> <td><b>Nome</b></td>";
     echo '<td>' . $row['nome'] . '</td>';
     echo '</tr>';
     echo "<tr> <td><b>Email</b></td>";
     echo '<td>' . $row['email'] . '</td>';
     echo '</tr>';
     echo "<tr> <td><b>Data</b></td>";
     echo '<td>' . date("d/m/Y", strtotime($row['data'])) . '</td>';
     echo '</tr>';
     echo "<tr> <td><b>Mensagem</b></td>";
     echo '<td>' . $row['msg'] . '</td>';
     echo '</tr>';
 }
 mysqli_free_result($result);
 echo '</table>';

Here I didn’t have much trouble with it, I just can’t give one <br/> between the data to separate and wanted to know how to limit the result, example, display only the first 3 records.

  • 1

    "give a <br/> between the data, "you mean leave space between the table rows?

  • Yes, a space only after the row Message of the table (which is the last row of a record, I tried to put br there after the last /tr but it did not, so it only gives space before the first record.

  • 1

    For this the best is to make a table for each row, but it is not very logical...

  • 1

    @Jorgeb. worked well with a table for each record, just putting <table> and </table> within the while, and after that I could use the br, etc, thank you.

  • 2

2 answers

4


To limit the number of results you can use the Mysql LIMIT:

SELECT * FROM comentarios ORDER BY data DESC LIMIT 3;

3

Try using the LIMIT Clause would look like this

$result = mysqli_query($conn, 'SELECT * FROM comentarios ORDER BY data DESC LIMIT 3');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.