Jump to content

foreach and DB output


pahunrepublic

Recommended Posts

I'm learning PHP and put to myself to a task. But I can't figure this out. It's about the foreach

 

There is this database called books with columns: isbn, author,title, price. The DB has records. I want to output certain records of certain columns:for example echo $books['title"];. I also would like to use some functions

 

I used the following code to titles listing for example:

 

function db_connect() {
   $result = new mysqli('localhost', 'root', 'password', 'books');
   if (!$result) {
      return false;
   }
   $result->autocommit(TRUE);
   return $result;
}
function get_book_details($isbn) {
  // query database for all details for a particular book
  if ((!$isbn) || ($isbn=='')) {
     return false;
  }
  $conn = db_connect();
  $query = "select * from books where isbn='".$isbn."'";
  $result = @$conn->query($query);
  if (!$result) {
     return false;
  }
  $result = @$result->fetch_assoc();
  return $result;
}
$book = get_book_details($isbn);
foreach($bookdetail as $isbn => $qty){
echo $book['title'];
}

 

 

but with no luck it gives this error: Warning: Invalid argument supplied for foreach() in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\lessons\basics\arrays\foreach.php on line 41

 

Any help would be appreciated.

 

Link to comment
https://forums.phpfreaks.com/topic/225795-foreach-and-db-output/
Share on other sites

  Quote

that error is telling you that $bookdetail is not an array. i suspect that should be foreach($book

I tried:

$book = get_book_details($isbn);
foreach($book as $isbn => $qty){
echo $book['title'];

 

because logic dictates but it gives the same error message

  Quote

you need to get your result into an array, so try and do

 

$bookdeatail = mysql_fetch_array($book);

 

then go ahead and try your foreach.

Ok the strange thing and where my problem is that in 

function get_book_details($isbn)

already gets the result into array

$result = @$result->fetch_assoc();

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.