How can variables be properly stored and retrieved when fetching data from a MySQL database in PHP?

When fetching data from a MySQL database in PHP, variables can be properly stored and retrieved by using the fetch_assoc() function to fetch data as an associative array. This allows you to access the values using the column names as keys. You can then store these values in variables for further processing.

// Connect to MySQL database
$conn = new mysqli($servername, $username, $password, $dbname);

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

// Fetch data from database
$sql = "SELECT * FROM table";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        $column1 = $row["column1"];
        $column2 = $row["column2"];
        // Process data or store in variables
    }
} else {
    echo "0 results";
}

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