How can PHP variables be used effectively within SQL queries to retrieve specific values?
When using PHP variables within SQL queries to retrieve specific values, it is important to properly sanitize the input to prevent SQL injection attacks. One way to do this is by using prepared statements with placeholders for the variables in the query. This allows the variables to be bound to the placeholders before executing the query, ensuring that the values are properly escaped.
// Example of using PHP variables in SQL query with prepared statements
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare and bind SQL statement with placeholders
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Set parameter values
$username = "john_doe";
// Execute the query
$stmt->execute();
// Get the result
$result = $stmt->get_result();
// Output the result
while ($row = $result->fetch_assoc()) {
echo "Username: " . $row["username"] . "<br>";
}
// Close the statement and connection
$stmt->close();
$conn->close();