How can PHP variables be properly escaped and integrated into SQL queries to prevent errors or vulnerabilities like SQL injections?

To prevent SQL injections, PHP variables should be properly escaped using prepared statements or parameterized queries. This method separates the SQL query logic from the user input, making it impossible for malicious SQL code to be injected. By using prepared statements, variables are automatically escaped by the database driver, ensuring the safety of the SQL query.

// Example code using prepared statements to prevent SQL injections
$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 statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");

// Bind parameters
$stmt->bind_param("s", $username);

// Set parameters and execute
$username = $_POST['username'];
$stmt->execute();

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

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

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