SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Aug 2013
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    PHP array from MySQL table not seeing first row

    Hi,

    I am using the following code to populate an array from a MySQL table but it does not seem to be collecting the first row?

    Code:
    $sql = "SELECT field1, field2, field3, .... FROM sometable";
    $result = mysql_query($sql) or die(mysql_error());
    
    $array = array();
    
    while($row = mysql_fetch_assoc($result)) {
       $array[] = $row;
    }
    
    echo $array[0]['field2']; // display field2 value from 1st row of result set.
    When I echo the above as is it show me the correct value for the second row not the first?

  2. #2
    SitePoint Guru bronze trophy
    Join Date
    Feb 2013
    Posts
    727
    Mentioned
    7 Post(s)
    Tagged
    0 Thread(s)
    $row is an array as well and I don't believe (not tried your approach) that can call a value without another key. It might be something like
    $array[0][0]['field2'];
    $array[1][1]['field2'];
    $array[2][2]['field2'];
    Not 100% sure but I would think you'll need to loop through with a foreach() statement. Adding this print code should give you a good view of the array structure.
    PHP Code:
    echo "<pre>";
    print_r($array);
    echo 
    "</pre>"

  3. #3
    SitePoint Member
    Join Date
    Aug 2013
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the info, I have tried your recommendation and the print_r shows the first as follows...
    Code:
    Array
    (
        [0] => Array
            (
                [id] => 2
                [No1] => 6
                [No2] => 12
                [No3] => 15
                [No4] => 16
                [No5] => 31
                [No6] => 44
            )
    Which is actually the second row in the table, this is puzzling

  4. #4
    SitePoint Member
    Join Date
    Aug 2013
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sorted Dreamwaver was already creating an associated array which I have now removed, problem sorted. Thank you Drummin for your reply and pointing me in the right direction.
    lol, now all i have to do is figure how to mark this as resolved


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
  •