What is the correct MySQL syntax for selecting data based on a specific condition in PHP?
When selecting data based on a specific condition in MySQL using PHP, you can use the SELECT statement with a WHERE clause to specify the condition. This allows you to filter the results based on a specific criteria, such as a certain value in a column or a combination of conditions. Make sure to properly sanitize any user input to prevent SQL injection attacks.
<?php
// 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);
}
// Select data based on a specific condition
$sql = "SELECT * FROM table_name WHERE column_name = 'specific_value'";
$result = $conn->query($sql);
// Display the results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Column 1: " . $row["column1_name"]. " - Column 2: " . $row["column2_name"]. "<br>";
}
} else {
echo "0 results";
}
// Close the connection
$conn->close();
?>