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; }
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.
$results
数组将返回,然后应在函数外部循环
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"];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.