I have this PHP function i am using to retrieve rows from a mysql database:
$stmt = $pdo_conn->prepare("SELECT * from admin where sequence > :sequence ");
$stmt->execute(array(':sequence' => $user_sequence));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
$results=array();
foreach($records as $results) {
return $results;
}
here i am calling the function:
$test = AdminUserSessionID2('2');
echo $test["forename"];
but it is only displaying one row, what have i done wrong which is making it not display all rows?
Why return
in foreach
? Of course it will return just the first row. It's like saying foreach(rows as row){ return row; }
.
<?php
function MyFunction($user_sequence){
global $pdo_conn;
$stmt = $pdo_conn->prepare("SELECT * from admin where sequence > :sequence;");
$stmt->execute(array(':sequence' => $user_sequence));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $records;
}
var_dump(MyFunction($user_sequence));
?>
You are assigning results as an empty array. Then assigning it as the first item of records and returning it.
Try:
foreach($records as $row) {
array_push($results, $row)
}
You can't return multiple data/results in a foreach loop, because the first return will end the function. It's better to return the full array/records and do a foreach loop outside the function.
The $results
array is getting returned, which should then be looped outside of the function
Try this:
function AdminUserSessionID2($user_sequence){
$stmt = $pdo_conn->prepare('SELECT * from admin where sequence > :sequence');
$stmt->execute(array(':sequence' => $user_sequence));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $records;
}
No-one has pointed out that return
will exit your current function directly preventing any further processing, and this is why you get just one row output. Your specific code based on what you want to achieve would be:
$stmt = $pdo_conn->prepare("SELECT * from admin where sequence > :sequence ");
$stmt->execute(array(':sequence' => $user_sequence));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
$results=array();
foreach($records as $results) {
$test = AdminUserSessionID2('2');
echo $test["forename"];
}