Yamaha32088
Yamaha32088

Reputation: 4163

Illegal string offset error

I am getting a couple errors when running my script:

Warning: Illegal string offset 'photo_id' in /var/www/BrandonsBlog/comments.php on line 35
Notice: Undefined offset: 2 in /var/www/BrandonsBlog/comments.php on line 35

My code:

    ini_set("display_errors", TRUE);
    include "Database.php";

    Class Database {
        protected $conn;

        public function setDb($conn){
            $this->conn = $conn;
        }
    }

    Class Images extends Database{
        protected $stmt;

        public function RetrieveImages(){

            $this->stmt = $this->conn->prepare('SELECT * FROM `pictures`');
            $this->stmt->execute();
            $boom = $this->stmt->fetchAll();
            return $boom;
        }
    }

    Class Content extends Images{

    }

    $test = new Images();
    $test->setDb($conn);
    $test2 = $test->RetrieveImages();

    var_dump($test2);
foreach ($test2 as $key => $value) {
    $photo_id = $value[$key]['photo_id'];
    //echo '<div class="hello" id="'.$photo_id.'"></div>';
}

The var_dump($test2); is giving me the following output:

array(3) {
  [0]=>;
  array(4) {
    ["id"]=>;
    string(1) "1"
    [0]=>;
    string(1) "1"
    ["photo_id"]=>;
    string(1) "1"
    [1]=>;
    string(1) "1"
  }
  [1]=>;
  array(4) {
    ["id"]=>;
    string(1) "2"
    [0]=>;
    string(1) "2"
    ["photo_id"]=>;
    string(1) "2"
    [1]=>;
    string(1) "2"
  }
  [2]=>;
  array(4) {
    ["id"]=>;
    string(1) "3"
    [0]=>;
    string(1) "3"
    ["photo_id"]=>;
    string(1) "3"
    [1]=>;
    string(1) "3"
  }
}

This is what my database table looks like that I am retrieving from:

mysql> select * from pictures;
+----+----------+
| id | photo_id |
+----+----------+
|  1 | 1        |
|  2 | 2        |
|  3 | 3        |
+----+----------+
3 rows in set (0.00 sec)

Could anyone tell me why I am getting this error and also in my var_dump() it seems that the values in each row are duplicated for some reason maybe this is causing my error?

Upvotes: 0

Views: 3333

Answers (2)

Pathik Gandhi
Pathik Gandhi

Reputation: 1344

Foreach give direct array value you dont need to get using key value.

Remove [$key] from the below foreach

foreach ($test2 as $key => $value) {
    $photo_id = $value['photo_id'];
    //echo '<div class="hello" id="'.$photo_id.'"></div>';
}

Upvotes: 1

Adam
Adam

Reputation: 1371

change this:

$photo_id = $value[$key]['photo_id'];

to this:

$photo_id = $value['photo_id'];

should work

Upvotes: 1

Related Questions