Skip to main content

Posts

Showing posts from August, 2021

Print total of a variable inside while loop outside of the loop

To accumulate values from a MySQL query inside a while loop and then calculate the total value outside the loop, you can use a variable to store the total value while iterating through the records. Here's an example in PHP: <?php // Your database connection parameters $servername = "localhost" ; $username = "your_username" ; $password = "your_password" ; $database = "your_database" ; // Create a connection to the MySQL database $conn = new mysqli( $servername , $username , $password , $database ); // Check the connection if ( $conn -> connect_error ) { die ( "Connection failed: " . $conn -> connect_error ); } $totalValue = 0 ; // Initialize total value // Your SQL query $sql = "SELECT value_column FROM your_table_name WHERE your_conditions" ; $result = $conn -> query ( $sql ); if ( $result -> num_rows > 0 ) { while ( $row = $result -> fetch_assoc ()) {