How can one ensure a secure connection between a PHP page and a MySQL database?
To ensure a secure connection between a PHP page and a MySQL database, you should use prepared statements to prevent SQL injection attacks. This involves using parameterized queries instead of directly inserting user input into SQL statements. Additionally, you should also make sure to properly sanitize and validate user input before sending it to the database.
// 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 prepared statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Set the username variable to a sanitized user input
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
// Execute the prepared statement
$stmt->execute();
// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Process the data
}
// Close the statement and connection
$stmt->close();
$conn->close();