How can one ensure a secure database connection and query execution when working with PHP and MySQL?

To ensure a secure database connection and query execution when working with PHP and MySQL, it is important to use prepared statements to prevent SQL injection attacks. This involves using parameterized queries to separate SQL code from user input. Additionally, always validate and sanitize user input before using it in a query.

// Establish a secure database connection
$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 and execute a secure query
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

$username = "user_input_here";
$stmt->execute();

$result = $stmt->get_result();

// Process the query result
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

$stmt->close();
$conn->close();