What are the best practices for handling MySQL queries in PHP to ensure proper data retrieval and manipulation?

When handling MySQL queries in PHP, it is important to use prepared statements to prevent SQL injection attacks and ensure proper data retrieval and manipulation. Prepared statements separate SQL logic from data input, making it safer to execute queries with user input. Additionally, using parameterized queries can improve performance by allowing the database to cache query execution plans.

// 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 query using a prepared statement
$stmt = $conn->prepare("SELECT * FROM table WHERE id = ?");
$id = 1;
$stmt->bind_param("i", $id);

// Execute the prepared statement
$stmt->execute();

// Bind the result variables
$stmt->bind_result($result);

// Fetch the results
while ($stmt->fetch()) {
    echo $result . "<br>";
}

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