Not sure what a PHP array does when assigned
I have a DB code snippet here ... I will post relevant lines without error checking to make it smaller ...
if ($stmt->bind_result($row[0], $row[1]) === false) etc...
then below I have ...
<pre><code>
//fill the array up with an array of rows, then increment $ddp.
//$data[$ddp] is the row,
//$data[$dpp][0] is the rows first argument,
//$data[$dpp][1] is the rows 2nd argument returned etc...
$ddp = 0; // this increments up every fetch
while ($stmt->fetch()) {
$data[$ddp][0] = $row[0];
$data[$ddp][1] = $row[1];
$ddp++;
}
</code></pre>
How I do it on WORKS ... but this is how I did it before and something strange was happening ...
<pre><code>
$ddp = 0; // this increments up every fetch
while ($stmt->fetch()) {
$data[$ddp++] = $row;
// I ECHOd out $row here... and it did fetch 2 different rows...
}
</code></pre>
What's going on ... when I did it ...
$data[$ddp++] = $row;
$data[0][0]
was the same as $data[1][0]
.
Why then, if $row
had different values for the two sets ... how $data
did you end up with two arrays the same?
I even tried
$data[] = $row;
and the same results. My fix was ...
while ($stmt->fetch()) {
$data[$ddp][0] = $row[0];
$data[$ddp][1] = $row[1];
$ddp++;
}
Why?
Sorry if this is not the right place to do this, but I found the solution ahead of time and saved time. I posted the answer and my question together.
source to share
Your two assignments do two subtly different things.
while ($stmt->fetch()) {
$data[$ddp][0] = $row[0];
$data[$ddp][1] = $row[1];
$ddp++;
}
This creates two entries in the array: the first will be indexed [0][0]
and assigned a value $row[0]
, etc.
On the other hand, these are:
while ($stmt->fetch()) {
$data[$ddp++] = $row;
// I ECHOd out $row here... and it did fetch 2 different rows...
}
adds one row to the database and appends all $row
to $data[0]
on first pass. This way, whatever is returned from the database is added as is - if you return an array from fetch()
, you are adding the array to your array.
source to share