Results 1 to 4 of 4
  1. #1
    Join Date
    Mar 2012
    Posts
    19

    Unanswered: Need help writing query that returns the same column from multiple rows

    I know the function mysql_fetch_array() receives one row returned by a query and puts it into an array with each index corresponding to one column of the row.

    I want to write a query that returns data in the same column from multiple rows, and how to put that data into an array so I can use it.

    If I write a query like this:
    Code:
    $this = SELECT column 4
                 From table1
                 WHERE column1 = value1 AND column2 = value2 AND column3 = value3;
    I want the result to combine the value contained in one column (the same column) from several rows. Column4 of each row is a number. I want the script to add all the numbers.

    Can I place that result in mysql_fetch_array() just like I would if the query returned data from just one row? In this case, would the "row" be the data from "that" column in each row returned?

    Thanks for your help

  2. #2
    Join Date
    Sep 2009
    Location
    San Sebastian, Spain
    Posts
    880
    You can have a look at GROUP_CONCAT which might help return all the information into a single row. However you will then need to separate each item within your PHP code using something like "explode" which converts the contents into an array for processing.
    Ronan Cashell
    Certified Oracle DBA/Certified MySQL Expert (DBA & Cluster DBA)
    http://www.it-iss.com
    Follow me on Twitter

  3. #3
    Join Date
    Nov 2004
    Location
    out on a limb
    Posts
    13,692
    Provided Answers: 59
    As this is a PHP question I've moved it to the PHP forum



    PHP Code:
    $ANumericVariable 0;
    while (
    $row=mysql_fetch_array($MySQLResultset)
    {  if 
    isnumeric($row[MyColumnName]) // Check the returned value actually is a number
       
    {  $ANumericVariable $ANumericVariable $row[MyColumnName];
       }  else 
    // do nothing as there is no point if its not numeric
       
    {
       }

    replace MyColumnName...with whatever your column is actually called
    I'd rather be riding on the Tiger 800 or the Norton

  4. #4
    Join Date
    Nov 2004
    Location
    out on a limb
    Posts
    13,692
    Provided Answers: 59
    ..of course if 'all' you want to do is sum the values in that column then a single SQL statement would be a smarter call. eg:-
    Code:
    SELECT SUM(MyColumn) AS MyColumnSum FROM MyTable.....
    I'd rather be riding on the Tiger 800 or the Norton

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •