How can PHP variables be properly defined and accessed when retrieving specific data from a database query?

When retrieving specific data from a database query in PHP, you can properly define and access variables by assigning the fetched data to the variables. You can use the mysqli_fetch_assoc() function to fetch an associative array of the query result, and then access the specific data using the column names as keys in the array.

// Assume $conn is the database connection and $query is the SQL query
$result = mysqli_query($conn, $query);

if($result){
    $row = mysqli_fetch_assoc($result);
    
    // Access specific data using column names
    $id = $row['id'];
    $name = $row['name'];
    $email = $row['email'];
    
    // Use the variables as needed
    echo "ID: $id, Name: $name, Email: $email";
}