How can PHP developers ensure data security in their code, especially when dealing with MySQL queries?

To ensure data security in PHP code when dealing with MySQL queries, developers should use prepared statements with parameterized queries. This helps prevent SQL injection attacks by separating SQL logic from user input data. By binding parameters to placeholders in the query, developers can ensure that user input is properly sanitized and secure.

// Establish a connection to the MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Prepare a SQL query with placeholders for parameters
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");

// Bind parameters to the placeholders and execute the query
$username = $_POST['username'];
$stmt->bind_param("s", $username);
$stmt->execute();

// Fetch the results and process them accordingly
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Handle the data retrieved from the database
}

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