I'm doing sth like this:
$q3 = $conn3->prepare("SELECT...");
$q3->bindParam(':param1', $param1);
$q3->execute();
$check3 = $q3->fetchAll(PDO::FETCH_ASSOC);
if (!empty($check3)){
$arr = array();
while($row = $q3->fetch(PDO::FETCH_ASSOC)) {
$arr[] = $row;
}
}
but I don't see the data in arr[] later on. What exactly am I doing wrong here? Is there a better way to fetch the data from mysql to an array in php?
fetch() returns the next row in the set. fetchAll() will fetch all the (remaining) rows and move the pointer to the last row, therefore fetch()
after fetchAll()
will not return anything because there will not be a next row in the set.
You need one or the other. To take advantage of fetchAll you could do:
$check3 = $q3->fetchAll(PDO::FETCH_ASSOC);
foreach ($check3 as $row) {
}
or just use fetch without fetchAll:
while ($row = $q3->fetch(PDO::FETCH_ASSOC)) {
}
Your code, as is, makes the fetch()
useless. You could just do:
$arr = $q3->fetchAll(PDO::FETCH_ASSOC);
Which is equivalent to:
$arr = array();
while($row = $q3->fetch(PDO::FETCH_ASSOC)) {
$arr[] = $row;
}
}