我试图在foreach语句中根据用户ID返回名字,但是它返回单词" array"作为第一个名字。我不知道为什么它会在场景中返回单词数组。
<table style="margin-top:-16px;">
<tbody style="overflow:hidden;">
<tr>
<th>Title</th>
<th>Author</th>
<th>Date Submitted</th>
<th>File Location</th>
<th>Download Status</th>
<th>Approve Status</th>
</tr>
<?php
$dbConnect = 'mysql:dbname=test;host=localhost';
$username = "test";
$password = "test";
try{
$dbConnect = new PDO($dbConnect, $username, $password);
} catch (PDOException $error) {
echo 'Error Connecting: ' . $error->getMessage();
}
$caseMgmtReturn = "SELECT * FROM `case`";
$caseMgmt = $dbConnect->query($caseMgmtReturn);
foreach ($caseMgmt as $row) {
$user = $row["userID"];
$firstPull = $dbConnect->prepare("SELECT `firstName` FROM `user` WHERE `userID`=:user");
$firstPull->bindValue(":user", $user);
$firstPull->execute();
$firstName = $firstPull->fetchAll(PDO::FETCH_ASSOC);
print "<tr> <td>" .$row["title"] . "</td> <td>" . $firstName . "</td> <td> " . $row["dateSubmitted"] . "</td> <td>" . $row["fileLocation"] . "</td> <td>" . $row["downloadStatus"] . "</td> <td>" . $row["approvedStatus"] ."</td></tr><br/>";
}
?>
</tbody>
</table>
答案 0 :(得分:1)
http://php.net/manual/en/pdostatement.fetchall.php
如果您要使用 - &gt; fetchAll(PDO :: FETCH_ASSOC),则需要引用相关的Key =&gt; Value对,例如
$firstName['firstName']
如果你使用 - &gt; fetch()它会返回一个基于索引的数组,所以你会像这样检索你的值;
$firstName[0]
您使用索引位置0,因为在您的SQL字符串中,您引用了表中的单个列,作为&#39; firstName&#39;。如果您使用
SELECT * FROM
然后你需要知道列在表中的顺序,这使得 - &gt; fetchAll(PDO :: FETCH_ASSSOC)非常有用。您没有引用数字,您引用了列名。
所以你的代码应该是这样的:
$firstPull = $dbConnect->prepare("SELECT `firstName` FROM `user` WHERE `userID`=:user");
$firstPull->bindValue(":user", $user);
$firstPull->execute();
$values = $firstPull->fetchAll(PDO::FETCH_ASSOC);
print "<tr> <td>" .$row["title"] . "</td> <td>" . $values['firstName'] . "</td> <td> " . $row["dateSubmitted"] . "</td> <td>" . $row["fileLocation"] . "</td> <td>" . $row["downloadStatus"] . "</td> <td>" . $row["approvedStatus"] ."</td></tr><br/>";