我正在尝试使用以下编码来获取所有行。在这里,您可以看到echo $row['UserName'];
和echo $row['Address'];
我可以从数据库中获取所有用户名和地址。但是当我在while循环之外使用这种编码($uname = $row['UserName'];echo $uname;
和$uaddress = $row['Address'];echo $uaddress;
)时,它总是获取最后一行的值。我的问题是如何获取while循环之外的所有行值?
<?php
include('config.php');
try
{
$stmt = $conn->prepare('SELECT * FROM ebusers');
$conn->errorInfo();
$stmt->execute();
while($row = $stmt->fetch())
{
echo "<a target=_blank href='edit.php?id=". $row['UserID'] ."'>Edit</a>";
echo "<br>";
echo "<a target=_blank href='delete.php?id=". $row['UserID'] ."'>Delete</a>";
echo $row['UserName'];
$uname = $row['UserName'];
echo "<br>";
echo $row['Address'];
$uaddress = $row['Address'];
echo "<br>";
}
}
catch(PDOException $e)
{
'Error : '.$e->getMesssage();
}
echo $uname;
echo $uaddress;
?>
答案 0 :(得分:0)
将它们传递给数组
while($row = $stmt->fetch())
{
echo "<a target=_blank href='edit.php?id=". $row['UserID'] ."'>Edit</a>";
echo "<br>";
echo "<a target=_blank href='delete.php?id=". $row['UserID'] ."'>Delete</a>";
echo $row['UserName'];
$uname[] = $row['UserName']; // An array of usernames...
echo "<br>";
echo $row['Address'];
$uaddress[] = $row['Address']; // An another array of addresses
echo "<br>";
}
//Below two statements prints all usernames and addresses
print_r($uname); // or you can access like echo $uname[2] to view the second username
print_r($uaddress); // similarly you can do like that as you did for $uname..
//or if you want to loop through individually , you can make use of a foreach construct
foreach($uname as $usernames)
{
echo $usernames."<br>";
}
答案 1 :(得分:0)
在while循环期间,$row
变量在每次执行时都会被覆盖。
您可以尝试FetchAll为您准备阵列。