What are best practices for structuring MySQL queries in PHP to avoid issues with data retrieval and manipulation?

When structuring MySQL queries in PHP, it is important to use prepared statements to prevent SQL injection attacks and ensure data integrity. Additionally, it is recommended to properly escape user input and handle errors gracefully to avoid issues with data retrieval and manipulation.

// Connect to the 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 statement with placeholders
$stmt = $conn->prepare("SELECT * FROM table WHERE column = ?");

// Bind parameters and execute the query
$value = "example";
$stmt->bind_param("s", $value);
$stmt->execute();

// Fetch results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Manipulate data here
}

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