What are the potential issues with using MySQL queries directly in PHP code?

Potential issues with using MySQL queries directly in PHP code include vulnerability to SQL injection attacks, difficulty in maintaining and updating queries, and reduced code readability. To solve this issue, it is recommended to use prepared statements with parameterized queries to prevent SQL injection attacks and improve security.

// Using prepared statements with parameterized queries to prevent SQL injection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Prepare a SQL query using a parameterized statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Set parameters and execute query
$username = "example_user";
$stmt->execute();

// Get result
$result = $stmt->get_result();

// Fetch data
while ($row = $result->fetch_assoc()) {
    echo "Username: " . $row["username"] . "<br>";
}

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