What are best practices for storing MySQL query results in PHP variables?

When storing MySQL query results in PHP variables, it is important to properly handle the data to prevent SQL injection attacks and ensure data integrity. One common approach is to use prepared statements with parameterized queries to sanitize input and prevent malicious code execution.

// 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 and execute a parameterized query
$stmt = $conn->prepare("SELECT id, name FROM users WHERE id = ?");
$stmt->bind_param("i", $id);

// Set the parameter value and execute the query
$id = 1;
$stmt->execute();

// Store the result in variables
$stmt->bind_result($userId, $userName);
$stmt->fetch();

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

// Now $userId and $userName contain the values retrieved from the database