Displaying "Sum()" in php

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • wbkski
    New Member
    • Nov 2014
    • 4

    Displaying "Sum()" in php

    Hello... total newb here... I know how to achieve a "sum" by using the following statement:
    SELECT SUM(Quantity) AS TotalItemsOrder ed FROM OrderDetails;

    but... I don't know how to display the result? I realize the "AS" is the column header for the answer but I don't know how to echo it.

    All help is appreciated.

    Thank you!
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    How do you currently echo a field that isn't a sum?

    Comment

    • wbkski
      New Member
      • Nov 2014
      • 4

      #3
      usually by assigning a variable and echoing the variable. But I can't find any examples where the "Sum()" function is used in a variable. And as mentioned before.. I'm new.

      Comment

      • Rabbit
        Recognized Expert MVP
        • Jan 2007
        • 12517

        #4
        Please post the code you use when it's not a sum.

        Comment

        • wbkski
          New Member
          • Nov 2014
          • 4

          #5
          Something like this...
          Code:
          <?php
          $servername = "localhost";
          $username = "username";
          $password = "password";
          $dbname = "myDB";
          
          // Create connection
          $conn = new mysqli($servername, $username, $password, $dbname);
          // Check connection
          if ($conn->connect_error) {
              die("Connection failed: " . $conn->connect_error);
          } 
          
          $sql = "SELECT id, firstname, lastname FROM MyGuests";
          $result = $conn->query($sql);
          
          if ($result->num_rows > 0) {
              // output data of each row
              while($row = $result->fetch_assoc()) {
                  echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
              }
          } else {
              echo "0 results";
          }
          $conn->close();
          ?>
          Last edited by Rabbit; Nov 8 '14, 07:08 PM. Reason: Please use [code] and [/code] tags when posting code or formatted data.

          Comment

          • Rabbit
            Recognized Expert MVP
            • Jan 2007
            • 12517

            #6
            Please use code tags when posting code or formatted data.

            So given your query above, on line 20 instead of something like $row["id"], use $row["TotalItemsOrde red"]

            Comment

            • wbkski
              New Member
              • Nov 2014
              • 4

              #7
              That worked. Thank you.

              Comment

              Working...