Limit database results?

5

Continuing with the lesson videos, I came across a method of displaying data from the database a bit differently, in the video it 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 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 did not have much of a problem with it, I just can not give <br/> between the data to separate and wanted to know how to limit the result, eg display only the first 3 records.

    
asked by anonymous 17.12.2015 / 17:15

2 answers

4

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

SELECT * FROM comentarios ORDER BY data DESC LIMIT 3;
    
17.12.2015 / 17:18
3

Try to use the LIMIT clause would look like this

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