How can PHP developers ensure the security of their MySQL connections and prevent SQL injection attacks in their code?

To ensure the security of MySQL connections and prevent SQL injection attacks in PHP code, developers should use prepared statements with parameterized queries. This approach allows developers to separate SQL logic from user input, preventing malicious SQL injection attacks.

// 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 with a parameterized query
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Set the parameter values and execute the statement
$username = $_POST['username'];
$stmt->execute();

// Process the results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Process each row
}

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