SitePoint Sponsor

User Tag List

Results 1 to 5 of 5

Hybrid View

  1. #1
    SitePoint Member
    Join Date
    Aug 2010
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    PHP Arrays and While Loops

    Hi

    The code I have written pulls in 3 rows from the database and at present puts the values into 1 array. Each row contains 12 values. Is there any way to place them into individual arrays each time it goes through the loop, creating 3 different arrays in total?

    The code I am using is:-

    $query=mysql_query("SELECT *FROM table1 WHERE TABLE1.COLUMNID=$value")

    while($row=mysql_fetch_row($query){
    some other code...}

    Thanks, Shane

  2. #2
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Welcome to Sitepoint Shane.

    Sure, the following will place all the rows found from the query in the $rows array.
    PHP Code:
    <?php
    $res  
    mysql_query(/**/);
    $rows = array();
    while(
    $row mysql_fetch_assoc($res)){
      
    array_push($rows$row);
    }
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  3. #3
    SitePoint Member
    Join Date
    Aug 2010
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Anthony

    Thanks for your prompt reply. I have implemented your code. I have now tried to echo the values of each of the arrays using:-

    for($x=0; $x<sizeof($row); $x++){
    echo $rows[$x]
    }

    but it comes back with the word 'array'.

    Thanks again, Shane

  4. #4
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Yep, that's right.

    $rows is an array of arrays.

    Let's say one the columns in your table is id, this is how we'd get at it.
    PHP Code:
    <?php
    $res  
    mysql_query(/**/);
    $rows = array();
    while(
    $row mysql_fetch_assoc($res)){
      
    array_push($rows$row);
    }


    foreach(
    $rows as $row){
      echo 
    $row['id'];
    }
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  5. #5
    SitePoint Member
    Join Date
    Aug 2010
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks Anthony, works a treat. :-)


Bookmarks

Posting Permissions

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