What are the best practices for handling SQL queries with strings and numbers in PHP?
When handling SQL queries with strings and numbers in PHP, it is important to properly sanitize and escape user input to prevent SQL injection attacks. One way to do this is by using prepared statements with parameterized queries. This helps separate the SQL query logic from the user input, ensuring that the input is treated as data rather than executable code.
// Example of using prepared statements to handle SQL queries with strings and numbers in PHP
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL query with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND age = :age");
// Bind parameters to the prepared statement
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->bindParam(':age', $age, PDO::PARAM_INT);
// Set the parameters
$username = "john_doe";
$age = 30;
// Execute the prepared statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Loop through the results
foreach ($results as $row) {
// Process each row as needed
echo $row['username'] . " is " . $row['age'] . " years old.<br>";
}