What best practices should be followed when handling database queries and retrieving numerical values in PHP to avoid type conversion errors and unexpected results?

When handling database queries and retrieving numerical values in PHP, it is important to ensure that the data types are consistent to avoid type conversion errors and unexpected results. One best practice is to explicitly cast numerical values to the desired data type before using them in calculations or comparisons. This can be done using functions like intval() or floatval() to convert strings to integers or floats, respectively.

// Example of retrieving a numerical value from a database query and casting it to the desired data type
$query = "SELECT price FROM products WHERE id = 123";
$result = $conn->query($query);
$row = $result->fetch_assoc();

// Cast the retrieved value to a float
$price = floatval($row['price']);

// Now $price can be safely used in calculations or comparisons
$total = $price * 10;
echo "Total price: $total";