user1930227
user1930227

Reputation: 105

saving strings into an array

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>";

}

Upvotes: 1

Views: 76

Answers (3)

Techie
Techie

Reputation: 45124

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);

Upvotes: 2

jeroen
jeroen

Reputation: 91734

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++;
}

Upvotes: 0

Teena Thomas
Teena Thomas

Reputation: 5239

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>";

Upvotes: 0

Related Questions