How can SQL Injections be prevented in PHP code that interacts with a MySQL database?
SQL Injections can be prevented in PHP code by using prepared statements and parameterized queries. This approach separates SQL code from user input, making it impossible for malicious input to alter the SQL query structure.
// Establish a connection to the MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Prepare a SQL statement with a parameterized query
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Set the parameter value and execute the query
$username = $_POST['username'];
$stmt->execute();
// Fetch the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Process the data
}
// Close the statement and connection
$stmt->close();
$mysqli->close();
Related Questions
- How can a variable be passed instead of a fixed name in a PHP script to retrieve values from a table column?
- How can the use of slashes in dynamic URLs affect the loading of CSS files in PHP applications?
- What is the best practice for handling form input values in PHP to ensure accurate calculations?