How can a value calculated in a SQL query be passed to a PHP script?
To pass a value calculated in a SQL query to a PHP script, you can store the result in a variable within the SQL query itself and then fetch that value in your PHP script. You can use the mysqli_fetch_array() or mysqli_fetch_assoc() functions to retrieve the calculated value from the query result set and store it in a PHP variable for further processing.
<?php
// Connect to the database
$conn = new mysqli("localhost", "username", "password", "database");
// Run the SQL query to calculate a value
$query = "SELECT SUM(column_name) AS total_sum FROM table_name";
$result = $conn->query($query);
// Fetch the calculated value and store it in a PHP variable
if($row = $result->fetch_assoc()) {
$totalSum = $row['total_sum'];
}
// Use the calculated value in your PHP script
echo "The total sum is: " . $totalSum;
// Close the database connection
$conn->close();
?>