1

I' m using the following code to get the desired details,that is, all the books that have the highest total count in order to show the most trending/popular books present in a website. The total column depicts the no. of times a particular book had been viewed by an user of the website. Here is the code`

<?php    
include("connection.php");
global $con;
$sql1= "SELECT book FROM vi_views ORDER BY total DESC LIMIT 3";
$query1= mysqli_query($con,$sql1);
if (!$query1)
{
  printf("Error: %s\n", mysqli_error($con));
  exit();
}
$obj1=mysqli_fetch_array($query1,MYSQLI_BOTH);
$row1=mysqli_num_rows($query1);
if ($row1>0)
{
  echo var_dump($obj1);
}
?>

Here is a look of how my table looks

Table:vi_views

id  book  course  date  total

1   book1  null  dd//mm/yy 3   
2   null   course1 dd/mm/yy 1    
3  book2   null dd/mm/yy 8    

and so on....

The problem is that the query is working but only the first record according to the query is shown, that is, book2 in this case and no more books are showing. where I'm lacking in my code please tell...

Isaac Bennetch
  • 11,830
  • 2
  • 32
  • 43

5 Answers5

1

You need to loop though the rows returned after execution of query.

$rowCount=mysqli_num_rows($query1);
if ($rowCount > 0)
{
  while ($row = mysql_fetch_array($result)) {
    echo var_dump($row);  // Can do something what you want to with data
  }
} else {
  echo 'No records';
}
Naincy
  • 2,953
  • 1
  • 12
  • 21
0

Change $obj1=mysqli_fetch_array($query1,MYSQLI_BOTH); to while($row = mysqli_fetch_array($query1)){ //do stuff } With fetch array you get only one row at the time

Bojan Radaković
  • 430
  • 3
  • 12
0

Try this:

$sql1= "SELECT book FROM vi_views ORDER BY total DESC LIMIT 3";
$query1= mysqli_query($con,$sql1);

while ($row = mysqli_fetch_assoc($query1)) {
    print_r($row);
}

or

   while ($row = mysqli_fetch_assoc($query1)) {
    //print_r($row);
    $book=$row['book'];echo "<br/>";
    echo $book;
}

output:

book1

book2

book3

NID
  • 3,238
  • 1
  • 17
  • 28
0

Please try this:

$obj1 = mysqli_fetch_array($query1,MYSQLI_BOTH);
while($row = mysqli_fetch_assoc($query1)){
  $book=$row['book'];
  echo var_dump($book);
}
jww
  • 97,681
  • 90
  • 411
  • 885
Jimm
  • 1
  • 1
0

You should loop the result.

$rowCount=mysqli_num_rows($query1);
if ($rowCount > 0)
{
  while ($row = mysql_fetch_assoc($result)) {
  echo "<pre>";
  print_r($row);
  echo "</pre>";
}
Salehin Rafi
  • 351
  • 2
  • 6
  • 16