How can PHP developers protect against SQL injection and what functions are commonly used for this purpose?
To protect against SQL injection in PHP, developers should use prepared statements with parameterized queries. This method separates the SQL query logic from the user input, preventing malicious SQL code from being executed. Commonly used functions for this purpose include mysqli_prepare() and bind_param().
// Establish a database connection
$mysqli = new mysqli("localhost", "username", "password", "database");
// Prepare a SQL statement using a parameterized query
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Set the parameter values and execute the query
$username = $_POST['username'];
$stmt->execute();
// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Handle the data
}
// Close the statement and connection
$stmt->close();
$mysqli->close();
Related Questions
- How can cheating by users be prevented effectively when updating properties based on a link click in PHP?
- How can the PHP manual be utilized to gain a better understanding of array functions and improve code quality in PHP programming?
- What are the best practices for handling asynchronous tasks in PHP, such as loading a webpage while running a background script?