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
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.