How can a beginner effectively query data from a MySQL database in PHP?
To query data from a MySQL database in PHP as a beginner, you can use the mysqli extension which provides an interface to interact with MySQL databases. You can establish a connection to the database, execute a SQL query to retrieve the data, and then fetch the results to use in your PHP code.
<?php
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Execute a SQL query to retrieve data
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Fetch and display the results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
// Close the connection
$conn->close();
?>
Related Questions
- What are the drawbacks of using onchange event with radio buttons in PHP forms?
- How does the use of PDO and prepared statements enhance security in PHP applications compared to other methods?
- In what scenarios should AJAX be used to split up HTTP requests for tasks in PHP, and how does it impact the user experience?