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
- In PHP, what is the correct syntax for accessing a specific column from a table in an Inner Join query in Oracle?
- What is the best approach to restructure a multidimensional array in PHP, grouping 'label' and 'value' in separate arrays?
- What are some potential reasons for a PHP page taking a long time to load on a local server?