What are some best practices for using SELECT statements in PHP to retrieve data from a MySQL database?

When using SELECT statements in PHP to retrieve data from a MySQL database, it is important to properly sanitize user input to prevent SQL injection attacks. It is also recommended to use prepared statements to improve performance and security. Additionally, fetching data using associative arrays or objects can make it easier to work with the retrieved data.

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

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

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

// Prepare and execute a SELECT statement
$stmt = $conn->prepare("SELECT id, name, email FROM users WHERE id = ?");
$stmt->bind_param("i", $id);

$id = 1;
$stmt->execute();
$result = $stmt->get_result();

// Fetch data using associative arrays
while ($row = $result->fetch_assoc()) {
    echo "ID: " . $row['id'] . " - Name: " . $row['name'] . " - Email: " . $row['email'] . "<br>";
}

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