Hi,

I'm struggling to get my head around this problem. All help, as usual greatly appreciated.

I want the array to look like this:

$gallery = array(
0 => array("location" => "images/001.jpg", "title" => "Image Title 1", "description" => "Image description number one"),
1 => array("location" => "images/002.jpg", "title" => "Image Title 2", "description" => "Image description number two")
);

This successfully allows me to use a foreach statement to blast through the images in the array:

foreach ($gallery as $image)
printf ("Title: %s Description: %s<br />", $image[title],$image[description]);
}

This seems to be working fine when the array is filled in manually.

However the problem comes when I try to load the array using information from a database.

I can't seem to figure out the correct syntax to populate a multidimensional array from a MySQL database.

Any ideas??

All help appreciated.

    the basics of the approach:

    while(){
    $gallery[]=array("location" => "??" ...);
    }
    

      Dagon,

      thank you for your reply.

      I'm one step closer to solving this, I know it's simple - I just don't fully understand the 'expression' part of the WHILE statement - therefore I'm not sure if i'm using it correctly.

      Also I don't fully understand how to pull the info from the db?

      Here is what I have so far (and many, many variants):

      $query = "SELECT * FROM images";
      $result = mysql_query($query) or die('Query failed: ' . mysql_error());
      $id = mysql_result ( $result, 0, "id" );
      $title = mysql_result ( $result, 0, "title" );
      $location = mysql_result ( $result, 0, "location" );
      $description = mysql_result ( $result, 0, "description" );
      
      $num=mysql_numrows($result);
      
      while($row = mysql_fetch_row($result)){
      $gallery[]=array("location" => $location,"title" => $title,"description" => $description);
      } 
      
      

      print_r($gallery);

      Array ( [0] => Array ( [location] => images/01.png [title] => Title 01 [description] => Description of image 01 ) [1] => Array ( [location] => images/01.png [title] => Title 01 [description] => Description of image 01 ) ) 
      

      The layout of the array seems perfect (I think?) However because I'm not understanding the use of mysql_* functions the WHILE statement - I'm running around in circles?

      I know I'm close, I also really enjoy solving these problems 'myself' so appreciate the vague replies - they help my learning!!

        In your snippet you're using two different methods of getting the results from the same dataset, something that is not recommended.

        [man]mysql_result()[/man] gets one cell of the dataset at a time and is slow (check the manual page).

        [man]mysql_fetch_row()[/man] on the other hand fetchs an entire row of the dataset, quicker.

        If you just wanted to fetch the first row of a result set (unlikely) the

        $row = mysql_fetch_row($result);

        would do it.

        The [man]while()[/man] loop loops through the result set until there are no more results, so

         while($row = mysql_fetch_row($result)){
        	$gallery[] =$row;
        }

        would create an array of the entire result set.

        But what think you are trying to achieve would be best done with [man]mysql_fetch_assoc()[/man] so that by doing this

        while($row = mysql_fetch_assoc($result)){
        	$gallery[] =$row;
        }

        you would get this type of result

        Array ( [0] => Array ( [location] => images/01.png 
        			[title] => Title 01 					
        			[description] => Description of image 01 ) 
        	[1] => Array ( [location] => images/01.png 
        			[title] => Title 01 
        			[description] => Description of image 01 ) )

        A tip to better see the structure of your arrays is to enclose them in <pre></pre> tags like this

        echo '<pre>';
        print_r($gallery);
        echo '</pre>';

          rincewind,

          I have been slogging away at trying to get this done, thought I was getting there - but I seemed to be going a VERY long way around.

          Until your post I didn't realise the array was automatically filled (I was trying to fill with each variable).

          Thanks for the <pre> tip

          Makes the array much more pleasing to the eye!

          So thanks to your genius, my code looks like this:

          $result = mysql_query($query) or die('Query failed: ' . mysql_error());
          
          while($row = mysql_fetch_assoc($result)){
              $gallery[] =$row;
          } 
          
          echo '<pre>';
          print_r($gallery);
          echo '</pre>';
          
          

          What's brilliant about this is the $gallery array can be print_r OUTSIDE of the loop, something I was having trouble with before your code simplified the whole process!

          Now, the next question:

          I was hoping to print the individual data from each array 'component' as and when I needed it - I do go about doing this?

          My first instinct:

          echo $gallery[1][title];
          

          Doesn't work - it just prints 'Array'??

          Any ideas?

            Yes the way your doing it is by printing off the results from inside the while loop. But at the same time you're creating an array in $gallery, so you could build up the code for your images into another variable like so

            while($image = mysql_fetch_array($result)){
            $display .= '<img src="'.$image['location'].'" /><br />'.$image['title'].'<br />'.$image['description']."<br />\n";
            }
            

            and then just echo out $display where you want it to appear in the code.
            Or you could use the [man]mysql_fetch_assoc()[/man], I assume your column names in your database are id, location, title and description. If they are then using

            while($row = mysql_fetch_assoc($result)){
            	$gallery[] =$row;
            }

            will do the exact same thing as your doing with this

            $gallery = array($image["id"] => array("location" => $image["location"],"title" => $image["title"],"description" => $image["description"]));

            You could then use a [man]for()[/man] loop to loop through the varaible $gallery and build up your html code.

            To me it is obviously easier an faster to do it this way

            while($row = mysql_fetch_assoc($result)){
            $display .= '<img src="'.$image['location'].'" /><br />'.$image['title'].'<br />'.$image['description']."<br />\n";
            }

            as your only getting the associative array rather than the associative and numeric.

              Rincewind,

              thank you for all your help.

              I actually edited my post (most likely when you were replying).

              I basically accepted that your way was much swifter and ditched my long winded attempt at creating an array.

              I then went on to say:

              Now, the next question:

              I was hoping to print the individual data from each array 'component' as and when I needed it - I do go about doing this?

              My first instinct:

              echo $gallery[1][title];
              Doesn't work - it just prints 'Array'??

              Any ideas?

                If you use the associative array then

                print $gallery[1]['title']; 

                would do it, you should have the single quotes around the name otherwise the parser look for a constant.

                  Works a treat!

                  Thank you.

                  So for future reference of those searching:

                  To create a Multidimension Array using data from a MySQL Database.

                  //Create Query
                  $query = "SELECT * FROM images";
                  //Store query in $Result
                  $result = mysql_query($query) or die('Query failed: ' . mysql_error());
                  // Use WHILE and mysql_fetch_assoc to loop through each row.
                  while($row = mysql_fetch_assoc($result)){
                      $gallery[] =$row;
                  } 
                  
                  

                  This will create the array:

                  Array
                  (
                      [0] => Array
                          (
                              [id] => 1
                              [location] => images/01.png
                              [title] => Title 01
                              [description] => Description of image 01
                          )
                  
                  [1] => Array
                      (
                          [id] => 2
                          [location] => images/02.png
                          [title] => Title 02
                          [description] => Description of image 02
                      )
                  
                  )

                  To view this array as above, use:

                  echo '<pre>';
                  print_r($gallery);
                  echo '</pre>';
                  

                  If you want to use individual elements of the array use:

                   print $gallery[1]['title']; 
                  

                  Replacing '1' with your row ID and 'title' with your Column Title.

                    Write a Reply...