Reputation: 45
I'm using the following code in order to get data from table and fetch it to object named Question :
$stmt = $conn->query("SELECT * FROM QA");
$stmt->setFetchMode(PDO::FETCH_INTO,new QA);
foreach($stmt as $qa){
var_dump($qa);
array_push($this->allQA,$qa);
}
The code above outputs :
object(QA)[5]
public 'question' => string 'first question' (length=14)
public 'answer' => string 'first answer' (length=12)
object(QA)[5]
public 'question' => string 'second question' (length=15)
public 'answer' => string 'second answer' (length=13)
However, var_dump($this->allQA);
outputs :
array (size=2)
0 =>
object(QA)[5]
public 'question' => string 'second question' (length=15)
public 'answer' => string 'second answer' (length=13)
1 =>
object(QA)[5]
public 'question' => string 'second question' (length=15)
public 'answer' => string 'second answer' (length=13)
Why does it happen ? why "first question first answer" doesn't appear at all while "second question second answer" appears twice?
Thanks in advance.
Upvotes: 1
Views: 65
Reputation: 45490
You set the fetch mode, but I didn't see you actually fetch the data:
$qas = stmt->fetchAll();
foreach($qas as $qa){
var_dump($qa);
array_push($this->allQA,$qa);
}
Upvotes: 0
Reputation: 887
Objects are by default passed by reference when pushing them along to the array, so when you modify the original object, all instances that you've put into the array will become modified too.
Here's where it goes wrong:
array_push($this->allQA, $qa);
For every loop, the variable $qa
receives the value of the next element of $stmt
. Since the values previously pushed onto the array have been pushed as references, it means that any modifications to $qa
will affect the previous values too. This results in all the values being equal to the last modification you did to $qa
, which is the second answer.
To fix it, you want to push a copy of the object to the array, and not a reference. This can be accomplished using the clone
-keyword:
array_push($this->allQA, clone $qa);
Upvotes: 1