Ryan
Ryan

Reputation: 11

mysqli fetch_assoc only 1 result instead of all

if ($result = $db->query("SELECT * FROM tab WHERE ID = $id")) {
while($row = $result->fetch_assoc() ){
echo "ID:". $row['ID'];
echo "Product:" .$row['Product'];
... }
$result->close();
} else {
echo "could not retrieve data from db";  }

I only get one result, but it should be a lot more. How do I get all the results?

btw I cannot use fetch_all.

Upvotes: 1

Views: 12279

Answers (4)

user7182340
user7182340

Reputation:

You must select both id and product from tab and also add a where statement.

Your code would look like:

  if ($result = $db->query("SELECT ID, Product, user FROM tab WHERE user='".$username."' ")) { //$username = john;
    while($row = $result->fetch_assoc() ){
      echo "ID:". $row['ID'];
      echo "Product:" .$row['Product'];
    }



  } else {
    echo "There is no data in the database"; 

  } result->close();

Let me hope your equate value is the name john it may be anything. so you will get all result rows from the database where the word john is listed.

put $username = 'john'; before the if statement.

Upvotes: 0

David Lemon
David Lemon

Reputation: 1560

You are using an ID in your query, that means that you are asking for a specific item. In order to select all you have to remove this condition.

Your code would look like:

  if ($result = $db->query("SELECT * FROM tab")) {
    while($row = $result->fetch_assoc() ){
      echo "ID:". $row['ID'];
      echo "Product:" .$row['Product'];
    }
    $result->close();
  } else {
    echo "There is no data in the database";  
  }

Upvotes: 2

Koen
Koen

Reputation: 140

Replace

$result = $db->query("SELECT * FROM tab WHERE ID = $id"

with

$result = $db->query("SELECT * FROM tab WHERE ID = $id LIMIT 1"

Upvotes: 1

Dite Gashi
Dite Gashi

Reputation: 128

The process of fetching data from a MYSQL result goes like this:

  • Connect to the host
  • Select the DB
  • Run the query

if ($result) //Check if the return is true

while($row = mysqli_fetch_array($result)) { // do something with the $row //like print it } }

In order to make fully sure print the query using

echo $your_query

Then run that query through phpMyAdmin and see what results or error you get.

Upvotes: -2

Related Questions