1

I've got a query which finds the top 10 most loaned books in my loan table, however i want to store these ten values into a single array so that I can then use the array again. Here is the code I have so far... Thanks for any help in advance!

//select a database to work with
$selected = mysql_select_db("ds2",$dbhandle)
or die("Could not select examples");

//execute the SQL query and return records
 $result = mysql_query("SELECT book.title, book.book_id, count(book.book_id) AS     count_book_id, loan.book_id  FROM book
      INNER JOIN loan ON book.book_id = loan.book_id
      GROUP BY book.book_id ASC
      ORDER BY count(book.book_id) DESC");

 $titles = array();

while($row = mysql_fetch_array($result))
{
echo $row['title'];
echo "<br>";
}

echo "<br><br>";

for($index = 1; $index <= 10; $index++)
{
array_push($titles,$result[$row]);
print_r($titles);
echo "<br>";

}
3
  • 2
    $titles[] = $row['title']; Commented Jan 11, 2013 at 17:19
  • Just FYI code makes bad assumption there will be 10 rows to iterate over. Think about a limit on the SQL and a foreach loop. Commented Jan 11, 2013 at 17:23
  • @ficuscr Yup, only reason I did that was because I wasn't sure how to save it into an array, in which case now I'll just have echo it once :) Commented Jan 11, 2013 at 17:24

3 Answers 3

2

Rather than echo $row['title'] You can use below code to store them into an array

$titles[] = $row['title'];

Use array notion to access them later.

$titles[0]; // 1st item
$titles[1]; //2nd item

You can even use a foreach loop to loop through all the items.

foreach($titles[] as $title)
     echo $title;

Below will allow you to get a comma separated string(Just for your information if you need it)

$comma_separated_titles = implode(",", $titles);
Sign up to request clarification or add additional context in comments.

Comments

0

Try,

while($row = mysql_fetch_array($result))
  {
      echo $row['title']; 
      $arr[] = $row['title'];  //Store in an array          
      echo "<br>";
  }

  echo "<br><br>";

  //Since you need only 10 values, else this for loop is not required.
  for($index = 1; $index <= 10; $index++) 
      $titles[] = $arr[$index]['title'];  

  unset($arr); //unset the original array if you don't need it anymore.
  print_r($titles); //Print top 10 values
  echo "<br>";

Comments

0

You should fill your array in the loop, not after it in a separate loop:

$count = 0;
while($row = mysql_fetch_array($result))
{
  echo $row['title'];
  echo "<br>";
  if ($count < 10)
  {
    array_push($titles, $row);
  }
  $count++;
}

1 Comment

@user1930227 Note that you need to push $row, I copied your code (wrongly...) before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.