Cannot use object of type stdClass as array

I’ve been trying to upgrade this script with no luck. I’m getting the following error.

PHP Fatal error: Uncaught Error: Cannot use object of type stdClass as array on line 17:

<?php
// determine script invocation (CLI or Web Server)
if(php_sapi_name() == 'cli') {
  $line_break = PHP_EOL;
} else {
  $line_break = '<br>';
} 
#index.php of our root
include_once 'file-uploading/dbconfig.php';


$sql = "SELECT * FROM `facebook` ORDER by rand() LIMIT 1";
$result = mysqli_query($link, $sql);


while($row = mysqli_fetch_object($result)) {
   $topic = htmlentities($row['topic']);
   $name = htmlentities($row['name']); 
   $file = htmlentities($row['file']);
   $description = htmlentities($row['description']);
}

Anyone know what’s wrong?

Thank you

The result set you are getting back from the query is an object, but you are trying to use array notation when you assign the values to variables - e.g. $name = htmlentities($row['name']);.

Note that htmlentities() is unnecessary if you’re working with UTF-8 consequently! the only function that is necessary is htmlspecialchars().

additionally, output escaping should be left to your output rendering engine. and even if you use PHP for that, array functions make that easier.

I done it this way:

while($row = mysqli_fetch_object($result)) {
   $topic = htmlentities(['topic']);
   $name = htmlentities(['name']); 
   $file = htmlentities(['file']);
   $description = htmlentities(['description']);
}

It works but the image doesn’t post and I get the following errors:

[18-Jan-2017 18:36:01 UTC] PHP Warning:  htmlentities() expects parameter 1 to be string, array given in /home/path/public_html/facebook/index.php on line 17
[18-Jan-2017 18:36:01 UTC] PHP Warning:  htmlentities() expects parameter 1 to be string, array given in /home/path/public_html/facebook/index.php on line 18
[18-Jan-2017 18:36:01 UTC] PHP Warning:  htmlentities() expects parameter 1 to be string, array given in /home/path/public_html/facebook/index.php on line 19
[18-Jan-2017 18:36:01 UTC] PHP Warning:  htmlentities() expects parameter 1 to be string, array given in /home/path/public_html/facebook/index.php on line 20
[18-Jan-2017 18:36:02 UTC] PHP Catchable fatal error:  Object of class mysqli_result could not be converted to string in /home/path/public_html/facebook/index.php on line 81

The error on line 81 is: $html .= $result;:

} else {
  $html = '<html><head>';
  $html .= '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">';
  $html .= '</head>';
  $html .= '<body>';
  $html .= $result;
  $html .= '</body>';
  $html .= '</html>';
  echo $html;
}

You’re using an object not an array, so it would be something like

$topic = $row->topic;

1 Like

Thanks everyone I got it fixed.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.