What is the correct PHP code to output only the first record from a MySQL database table?
When fetching data from a MySQL database table, you can use the `LIMIT` clause in your SQL query to retrieve only the first record. This is useful when you only need to display or work with a single record from the database. By adding `LIMIT 1` to your query, you can ensure that only the first row is returned.
<?php
// Connect to the database
$conn = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to select the first record from the table
$sql = "SELECT * FROM table_name LIMIT 1";
$result = $conn->query($sql);
// Output the first record
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo "ID: " . $row["id"] . " - Name: " . $row["name"];
} else {
echo "0 results";
}
// Close connection
$conn->close();
?>
Related Questions
- What are the advantages and disadvantages of using a NAS server for storing and streaming media files over HTTP?
- What are some best practices for securely handling FTP credentials in PHP scripts?
- What are the advantages and disadvantages of using Ajax in conjunction with PHP for handling Google Login authentication?