How can SQL Injections be prevented in PHP when writing to a MySQL database?
SQL Injections can be prevented in PHP when writing to a MySQL database by using prepared statements and parameterized queries. This method ensures that user input is treated as data rather than executable code, making it impossible for malicious SQL commands to be injected into the query.
// Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Prepare a SQL statement using a parameterized query
$stmt = $conn->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
$stmt->bind_param("ss", $value1, $value2);
// Set the values of the parameters and execute the query
$value1 = "input_value1";
$value2 = "input_value2";
$stmt->execute();
// Close the statement and the database connection
$stmt->close();
$conn->close();