What are best practices for handling user input and storing it in a MySQL database using PHP to prevent SQL injection attacks?
SQL injection attacks occur when user input is not properly sanitized before being used in SQL queries, allowing malicious users to execute unauthorized SQL commands. To prevent SQL injection attacks, it is important to use prepared statements and parameterized queries when interacting with a MySQL database in PHP. This ensures that user input is treated as data rather than executable code.
// Establish a connection to the MySQL database
$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);
}
// Prepare a SQL statement using a parameterized query
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $password);
// Sanitize and bind user input to parameters
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
// Execute the prepared statement
$stmt->execute();
// Close the connection
$stmt->close();
$conn->close();