What are the best practices for handling SQL queries in PHP scripts?

When handling SQL queries in PHP scripts, it is important to use prepared statements to prevent SQL injection attacks and ensure data security. Prepared statements separate SQL logic from data input, allowing the database to distinguish between code and data. This helps to protect against malicious input and ensures that data is properly sanitized before being executed.

// Establish 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 bind SQL statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

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

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

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