What is the purpose of using LIMIT in a SQL query when fetching data in PHP?
Using LIMIT in a SQL query when fetching data in PHP allows you to control the number of records returned by the query. This can be helpful when you only need a certain number of results, such as displaying a limited number of items on a page or fetching a subset of data for processing. By using LIMIT, you can improve the performance of your application by reducing the amount of data that needs to be retrieved and processed.
// 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);
}
// Fetch data with LIMIT
$sql = "SELECT * FROM table_name LIMIT 10"; // Fetching only 10 records
$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();