Jump to content

How to get the result into array


pahunrepublic

Recommended Posts

I'm self-studying PHP and put to myself to a task. But I can't figure this out. It's about putting a database result into array.

 

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 to use 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($book as $isbn => $qty){
echo $book['title'];
}

 

I have this error: Warning: Invalid argument supplied for foreach() in ..\foreach.php on line 41

I'm guessing that $book is not array that's why I get this error message. But the big problem is as you can see in the function

function get_book_details($isbn)

inside the function it already gets the result into array

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

 

Link to comment
https://forums.phpfreaks.com/topic/225867-how-to-get-the-result-into-array/
Share on other sites

You need to remove the @ from in front of your statements.

 

If you were getting php errors on those statements, it meant they weren't working. Hiding the errors doesn't make them go a way. Your code still won't work, but with the @ in the code, you won't know which statement is causing all the follow-on errors.

use var_dump($book) to see what $book is. If it's not an array, go backward to figure out why.

 

tip: remove @ from everywhere except in email addresses.

To try your tip. I did var_dump($book) and turns out to be boolean bool(false) so it's not an array that for sure. I just can't figure this out please someone help or give me a clue.

first, i would remove all @ symbols...

 

it's hard to tell what the problem is just by looking at the code. i would need to add debug code to check things out. i guess i would work from connecting to the database forward, as the SQL query seems straightforward. i would start by making sure the connection works, and move forward. i use die() each time, because i like execution to stop when it's pointless to continue, but echo() or whatever.

 

i would update db_connect() as follows. and if that doesn't show an error, update get_book_details similarly, adding echo or die() along each step to see what variable or condition is causing failure.

 

if (!$result) {
die(mysqli_error());
      return false;
}

first, i would remove all @ symbols...

 

it's hard to tell what the problem is just by looking at the code. i would need to add debug code to check things out. i guess i would work from connecting to the database forward, as the SQL query seems straightforward. i would start by making sure the connection works, and move forward. i use die() each time, because i like execution to stop when it's pointless to continue, but echo() or whatever.

 

i would update db_connect() as follows. and if that doesn't show an error, update get_book_details similarly, adding echo or die() along each step to see what variable or condition is causing failure.

 

if (!$result) {
die(mysqli_error());
      return false;
}

 

Like this????

function db_connect() {
   $result = new mysqli('localhost', 'root', 'password', 'books');
   if (!$result) {
   die(mysqli_error($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=='')) {
  die(mysqli_error($isbn));
     return false;
  }
  $conn = db_connect();
  $query = "select * from books where isbn='".$isbn."'";
  $result = $conn->query($query);
  if (!$result) {
  die(mysqli_error($result));
     return false;
  }
  $result = $result->fetch_assoc();
  return $result;
}
$book = get_book_details($isbn);
foreach($book as $isbn => $qty){
echo $book['title'];
}

 

Sorry if it seems a bit dumb but I am a learner. I get the same error though.

<?php

function db_connect() {
   $result = new mysqli('localhost', 'root', 'password', 'books');
   if (!$result) {



   die(mysqli_error($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=='')) {



  die(mysqli_error($isbn));
     return false;
  }
  $conn = db_connect();
  $query = "select * from books where isbn='".$isbn."'";
  $result = $conn->query($query);
  if (!$result) {



  die(mysqli_error($result));
     return false;
  }
  $result = $result->fetch_assoc();
  return $result;
}
$book = get_book_details($isbn);

//Not sure if I understood this right, however lets say Title is a field in your table.  You can get an array of all the titles
//from your query doing something like this.

$book_title = array();
while($rows = mysql_fetch_array($book)) {
    
    $book_item[] = $book['title'];
}

print_r($book_title);



?>

"//Not sure if I understood this right, however lets say Title is a field in your table.  You can get an array of all the titles

//from your query doing something like this."

 

No I want a list from the database. For example: if I put

echo $book['title'];

then it shows a list of the titles of the books in the database or if I put echo $book['author']; then it shows a list of the authors of the books in the database ...and so.. on

 

Well then there are a few ways to do it.

 

<?php

function db_connect() {
   $result = new mysqli('localhost', 'root', 'password', 'books');
   if (!$result) {





   die(mysqli_error($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=='')) {





  die(mysqli_error($isbn));
     return false;
  }
  $conn = db_connect();
  $query = "select * from books where isbn='".$isbn."'";
  $result = $conn->query($query);
  if (!$result) {





  die(mysqli_error($result));
     return false;
  }
  $result = $result->fetch_assoc();
  return $result;
}
$book = get_book_details($isbn);

//Not sure if I understood this right, however lets say Title is a field in your table.  You can get an array of all the titles
//from your query doing something like this.

$book_title = array();
while($rows = mysql_fetch_array($book)) {
    
$book_title[] = $rows['title'];
$book_auther[] = $rows['authoer'];
}

//you can loop out each field you want.
foreach ($book_title AS $title){

echo $title;

//Or another way is to just do it inside your while loop.

while($rows = mysql_fetch_array($book)) {
    
  echo $rows['title'];
echo "<br/>";
echo $rows['authoer'];
}

}






?>

Well then there are a few ways to do it.

 

<?php

function db_connect() {
   $result = new mysqli('localhost', 'root', 'password', 'books');
   if (!$result) {





   die(mysqli_error($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=='')) {





  die(mysqli_error($isbn));
     return false;
  }
  $conn = db_connect();
  $query = "select * from books where isbn='".$isbn."'";
  $result = $conn->query($query);
  if (!$result) {





  die(mysqli_error($result));
     return false;
  }
  $result = $result->fetch_assoc();
  return $result;
}
$book = get_book_details($isbn);

//Not sure if I understood this right, however lets say Title is a field in your table.  You can get an array of all the titles
//from your query doing something like this.

$book_title = array();
while($rows = mysql_fetch_array($book)) {
    
$book_title[] = $rows['title'];
$book_auther[] = $rows['authoer'];
}

//you can loop out each field you want.
foreach ($book_title AS $title){

echo $title;

//Or another way is to just do it inside your while loop.

while($rows = mysql_fetch_array($book)) {
    
  echo $rows['title'];
echo "<br/>";
echo $rows['authoer'];
}

}






?>

 

I tried both solution. The problem still remains $book variable is not an array. function get_book_details doesn't make it array

I'm Still working on a solution so I changed the code a little bit.

 

function db_connect() {
   $result = new mysqli('localhost', 'root', 'eunice', 'books');
   if (!$result) {
   die(mysqli_error($result));
      return false;
   }
   $result->autocommit(TRUE);
   return $result;
}
function get_book_details($result) {
  // query database for all details for a particular book
  $conn = db_connect();
  $query = "select * from books";
  $result = $conn->query($query);
  if (!$result) {
  die(mysqli_error($result));
     return false;
  }
  $result = $result->fetch_assoc();
  return $result;
}
$book = get_book_details($result);
if (is_array($book)){
foreach($book as $isbn => $qty){
echo $book['author'].'</br>';
echo $book['title'].'</br>';
}
}
else{
echo '$book variable is not an array';
}

the Output  of the above code is:

Example author no 1

Example title no 1

Example author no 1

Example title no 1

Example author no 1

Example title no 1

Example author no 1

Example title no 1

 

I got the database and $book is an array but the problem is now I only get the first record of the database and shows it 4 times.

What Am I missing here? I'm so close I know. Please any help

I'm Still working on a solution so I changed the code a little bit.

 

function db_connect() {
   $result = new mysqli('localhost', 'root', 'eunice', 'books');
   if (!$result) {
   die(mysqli_error($result));
      return false;
   }
   $result->autocommit(TRUE);
   return $result;
}
function get_book_details($result) {
  // query database for all details for a particular book
  $conn = db_connect();
  $query = "select * from books";
  $result = $conn->query($query);
  if (!$result) {
  die(mysqli_error($result));
     return false;
  }
  $result = $result->fetch_assoc();
  return $result;
}
$book = get_book_details($result);
if (is_array($book)){
foreach($book as $isbn => $qty){
echo $book['author'].'</br>';
echo $book['title'].'</br>';
}
}
else{
echo '$book variable is not an array';
}

the Output  of the above code is:

Example author no 1

Example title no 1

Example author no 1

Example title no 1

Example author no 1

Example title no 1

Example author no 1

Example title no 1

 

I got the database and $book is an array but the problem is now I only get the first record of the database and shows it 4 times.

What Am I missing here? I'm so close I know. Please any help

 

You need to call your associative array in a while loop.

 

$i=0;
while($result = $result->fetch_assoc()){
       $results[$i] = $result;
       $i++;
}

foreach($results as $result){
       echo $result.'<br>'; //Or whatever you want to do...
}

You need to call your associative array in a while loop.

 

$i=0;
while($result = $result->fetch_assoc()){
       $results[$i] = $result;
       $i++;
}

foreach($results as $result){
       echo $result.'<br>'; //Or whatever you want to do...
}

 

And how would you put your solution using the function get_book_details($result)? I want to use 2 functions for this. I had a similar solution earlier and it works:

function db_connect() {
   $result = new mysqli('localhost', 'root', 'eunice', 'books');
   if (!$result) {
   die(mysqli_error($result));
      return false;
   }
   $result->autocommit(TRUE);
   return $result;
}
$conn = db_connect();
  $query = "SELECT * FROM books";
  $result = $conn->query($query);
  /*$result->fetch_assoc() Returns an associative array that 
  corresponds to the fetched row or NULL if there are no more rows.*/
while($row = $result->fetch_assoc()) 
{
echo $row['isbn'].'</br>';
echo $row['author'].'</br>';
echo $row['title'].'</br>';
echo $row['price'].'</br>';
}

 

but without function get_book_details.  any solutions? Can I put the while loop into the functions?

You need to call your associative array in a while loop.

 

$i=0;
while($result = $result->fetch_assoc()){
       $results[$i] = $result;
       $i++;
}

foreach($results as $result){
       echo $result.'<br>'; //Or whatever you want to do...
}

 

And how would you put your solution using the function get_book_details($result)? I want to use 2 functions for this. I had a similar solution earlier and it works:

function db_connect() {
   $result = new mysqli('localhost', 'root', 'eunice', 'books');
   if (!$result) {
   die(mysqli_error($result));
      return false;
   }
   $result->autocommit(TRUE);
   return $result;
}
$conn = db_connect();
  $query = "SELECT * FROM books";
  $result = $conn->query($query);
  /*$result->fetch_assoc() Returns an associative array that 
  corresponds to the fetched row or NULL if there are no more rows.*/
while($row = $result->fetch_assoc()) 
{
echo $row['isbn'].'</br>';
echo $row['author'].'</br>';
echo $row['title'].'</br>';
echo $row['price'].'</br>';
}

 

but without function get_book_details.  any solutions? Can I put the while loop into the functions?

 

Anything you can do at the procedural level can be done inside of a function, or as a method of an object.

Ok maybe something like this. I tried :shrug:

function db_connect() {
   $result = new mysqli('localhost', 'root', 'password', 'books');
   if (!$result) {
   die(mysqli_error($result));
      return false;
   }
   $result->autocommit(TRUE);
   return $result;
}
function get_book_details($result) {
  // query database for all details for a particular book
  $conn = db_connect();
  $query = "select * from books";
  $result = $conn->query($query);
  if (!$result) {
  die(mysqli_error($result));
     return false;
  }  
  $i=0;
while($result = $result->fetch_assoc()){
   $results[$i] = $result;
       $i++;
}

foreach($results as $result){
       return $result.'<br>'; //Or whatever you want to do...
}
  

}//ends the function
$book = get_book_details($result);
echo $book['author'].'</br>';
echo $book['title'].'</br>';

 

It gives me the following error: Fatal error: Call to a member function fetch_assoc() on a non-object in

this line causes the (assumed object) $result to be overwritten with $result->fetch_assoc(), so the next loop $result is no longer an object.

 

while($result = $result->fetch_assoc()){ // $result is no longer the object $result. Now it is the array fetch_assoc()

 

you need to use a different variable name for $result.

Here is the solution:

function db_connect() {
   $result = new mysqli('localhost', 'root', 'password', 'books');
   if (!$result) {
   die(mysqli_error($result));
      return false;
   }
   $result->autocommit(TRUE);
   return $result;
}
function get_book_details(&$into)
{
    $conn = db_connect();
    $query = "select * from books";
    $result = @$conn->query($query);
    if ($result)
    {
        while ($row = $result->fetch_assoc())
        {
            $into[] = $row;
        }
    }
    else
    {
        // Not sure if you actually want to die or do something more graceful.
        die(mysql_error());
    } 
}

// ... some stuff
$results = array();
get_book_details($results);
foreach ($results AS $record)
{
    printf('Author: %s, Title: %s' . PHP_EOL, $record['author'], $record['title'].'</br>');
printf('ISBN: %s, Price: %s' . PHP_EOL, $record['isbn'], $record['price'].'</br>');
}

 

THANX FOR EVERYONE TO KEEP THIS THREAD ALIVE

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.