How can beginners effectively utilize LIMIT in PHP for data retrieval?
When retrieving data from a database in PHP, beginners can effectively utilize the LIMIT clause to control the number of records returned. This can be useful for pagination or limiting the amount of data displayed on a page. By using LIMIT in conjunction with an SQL query, beginners can easily retrieve a specific number of records from the database.
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Retrieve data with LIMIT
$sql = "SELECT * FROM table_name LIMIT 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();