我有这个PHP函数用于从mysql数据库中检索行:
$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;
}
这里我正在调用函数:
$test = AdminUserSessionID2('2');
echo $test["forename"];
但它只显示一行,我做错了什么使它不显示所有行?
答案 0 :(得分:0)
return
为什么foreach
?当然它只返回第一行。这就像说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));
?>
答案 1 :(得分:0)
您将结果指定为空数组。 然后将其指定为第一项记录并将其返回。
尝试:
foreach($records as $row) {
array_push($results, $row)
}
答案 2 :(得分:0)
您不能在foreach循环中返回多个数据/结果,因为第一个返回将结束该函数。最好返回完整的数组/记录,并在函数外部执行foreach循环。
答案 3 :(得分:0)
返回$results
数组,然后应该在函数
答案 4 :(得分:0)
试试这个:
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;
}
答案 5 :(得分:0)
没有人指出return
会直接退出当前函数,阻止进一步处理,这就是为什么你只得到一行输出。您的具体代码基于您希望实现的目标:
$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"];
}