What best practices should be followed when handling SQL queries in PHP scripts?
When handling SQL queries in PHP scripts, it is important to use prepared statements to prevent SQL injection attacks. Prepared statements separate SQL logic from user input, making it safer to execute queries. Additionally, always validate and sanitize user input to ensure data integrity and security.
// Establish a database connection
$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);
}
// Use prepared statements to prevent SQL injection
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Sanitize and validate user input
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
// Execute the query
$stmt->execute();
$result = $stmt->get_result();
// Process the results
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close the connection
$stmt->close();
$conn->close();
Related Questions
- How can one ensure access to all classes within an included PHP file in PHP?
- How does the strtr function in PHP compare to the str_replace function when it comes to replacing special characters in a string?
- What are the potential risks or drawbacks of using header() to redirect to an external URL for image retrieval?