在php函数中显示来自mysql的多行

在php函数中显示来自mysql的多行

问题描述:

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?

我使用这个PHP函数从mysql数据库中检索行: p>

  $ 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; 
}  
  code>  pre> 
 
 

这里我正在调用函数: p>

  $ test = AdminUserSessionID2('2'); 
echo  $ test [“forename”]; 
  code>  pre> 
 
 

但它只显示一行,我做错了什么使它不显示所有行? p > div>

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"];
}

See: http://php.net/return