What is the correct syntax for fetching data from a MySQL query in PHP?
When fetching data from a MySQL query in PHP, you need to use the appropriate PHP functions to execute the query and retrieve the results. The correct syntax involves using functions like mysqli_query() to execute the query, mysqli_fetch_assoc() or mysqli_fetch_array() to fetch the data, and mysqli_free_result() to free the memory associated with the result set. Make sure to handle errors and sanitize user input to prevent SQL injection attacks.
<?php
// Establish a connection to the database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Execute a query
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);
// Fetch data and display it
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "Name: " . $row["name"] . "<br>";
}
} else {
echo "No results found";
}
// Free the result set
mysqli_free_result($result);
// Close the connection
mysqli_close($connection);
?>