How can you ensure a secure connection to the database when using MySQLi in PHP?

To ensure a secure connection to the database when using MySQLi in PHP, you should use prepared statements to prevent SQL injection attacks. This involves binding parameters to the query instead of directly inserting user input, which helps to sanitize the input data. Additionally, you should always use secure passwords and restrict database user permissions to minimize the risk of unauthorized access.

<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Use prepared statements to secure queries
$stmt = $conn->prepare("SELECT * FROM your_table WHERE id = ?");
$stmt->bind_param("i", $id);

// Execute the query
$stmt->execute();

// Process the results

// Close the connection
$stmt->close();
$conn->close();
?>