What is the recommended practice for preventing SQL injection in PHP code?
SQL injection can be prevented in PHP code by using prepared statements with parameterized queries instead of directly inserting user input into SQL queries. This helps to separate the SQL code from the user input, preventing malicious SQL queries from being executed.
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Prepare a SQL statement using a parameterized query
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Set the parameter values and execute the query
$username = $_POST['username'];
$stmt->execute();
$result = $stmt->get_result();
// Fetch and process the results
while ($row = $result->fetch_assoc()) {
// Process the results here
}
// Close the statement and connection
$stmt->close();
$conn->close();
Related Questions
- How important is it for developers to continuously update their PHP knowledge and skills, especially with new versions and deprecated functions?
- Are there any best practices for validating XML files in PHP using the DOMDocument class?
- What are the advantages and disadvantages of using the Apigility framework for PHP?