What is the purpose of the database query in the PHP code provided?
The purpose of the database query in the PHP code provided is to retrieve data from a database table. To solve this issue, we need to ensure that the database connection is properly established and that the query is executed correctly to fetch the desired data.
// Establish a connection 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);
}
// Query to retrieve data from a table
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Check if the query was successful
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. "<br>";
}
} else {
echo "0 results";
}
// Close the database connection
$conn->close();