0

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?

1
  • You error is very clear. It gives you full information. String index can't be anything, but non-negative integer. Your error contains info - which line it is, so use var_dump() to discover why your index is illegal Commented Nov 19, 2013 at 6:39

2 Answers 2

1

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>';
}
Sign up to request clarification or add additional context in comments.

Comments

1

change this:

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

to this:

$photo_id = $value['photo_id'];

should work

Comments

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.