0

I am trying to get the result from my database table tbl_newpage but it throws error. I don't know why it throws error

The following line

   $page = $mysqli->real_escape_string($_GET['page']);

   $result=array();

   if($stmt = $mysqli->prepare("select * from tbl_newpage where name=?")){

     $stmt->bind_param("s", $page);

     $stmt->execute();

     $result = $stmt->get_result();

     while($row = $result->fetch_array()){

       $result[] = array($row); //This is where the error appears 
                echo "hello ";print_r($row);die();

     }

     $objSmarty->assign("result", $result);
   }

Throws error

Fatal error: Cannot use object of type mysqli_result as array in /var/www/html/examplesite/phpfile.php on line 22

3
  • add comment in the code on the error line Commented Jul 15, 2016 at 5:15
  • 3
    Change $result[] array to some other name something like $data because $result array store value of get_result() Commented Jul 15, 2016 at 5:16
  • @Saty Thank you very much Commented Jul 15, 2016 at 5:18

2 Answers 2

3

You're using the same variable $result for both the result of $stmt->get_result() and also the array of values that you're fetching. So on the second iteration of the loop, when it does

$row = $result->fetch_array()

$result no longer contains the mysqli result, it contains the array, and you can't call fetch_array() on an array. Use different variable names for them.

$output = array();
while ($row = $result->fetch_array()) {
    $output[] = $row;
}
$objSmarty->assign("result", $output);

Also, $row is already an array, you probably don't want to nest it in another array before pushing it onto the $output array.

Sign up to request clarification or add additional context in comments.

Comments

3

Try by changing final result as finalResult

 $page = $mysqli->real_escape_string($_GET['page']);

 $finalResult=array();

 if($stmt = $mysqli->prepare("select * from tbl_newpage where name=?")){

 $stmt->bind_param("s", $page);

 $stmt->execute();

 $result = $stmt->get_result();

 while($row = $result->fetch_array()){

   $finalResult[] = array($row);
            echo "hello ";print_r($row);die();

 }

 $objSmarty->assign("result", $finalResult);
 }

1 Comment

Thanks, that's the problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.