pahunrepublic Posted January 26, 2011 Share Posted January 26, 2011 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. Quote Link to comment Share on other sites More sharing options...
BlueSkyIS Posted January 26, 2011 Share Posted January 26, 2011 that error is telling you that $bookdetail is not an array. i suspect that should be foreach($book Quote Link to comment Share on other sites More sharing options...
tomtimms Posted January 26, 2011 Share Posted January 26, 2011 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. Quote Link to comment Share on other sites More sharing options...
pahunrepublic Posted January 27, 2011 Author Share Posted January 27, 2011 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 Link to comment Share on other sites More sharing options...
pahunrepublic Posted January 27, 2011 Author Share Posted January 27, 2011 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(); Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.