What is the best way to retrieve specific data from a MySQL database using PHP?
To retrieve specific data from a MySQL database using PHP, you can use the mysqli extension in PHP. You need to establish a connection to the database, write a SQL query to select the specific data you want, execute the query, and then fetch the results. Finally, you can loop through the results to display or use the data as needed.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to retrieve specific data
$sql = "SELECT column1, column2 FROM table WHERE condition";
$result = $conn->query($sql);
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";
}
$conn->close();
?>
Related Questions
- How can PHP and MySQL be used to ensure that past dates are not continuously prompted for marking usage if a space was not utilized?
- In PHP, what are the best practices for handling form submissions and extracting button names for further processing in the code?
- Are there any best practices or recommendations for optimizing PHP code when working with large XML files to improve performance and avoid errors like unclosed tokens?