【发布时间】:2015-04-22 13:44:09
【问题描述】:
我在这里有一些代码,我觉得可以提高效率。我一直在构建一个图书馆目录数据库,并且正在寻找一种方法来将从 SQL 数据库中提取的多个列(具有多个条目)存储到一个 PHP 数组中。这意味着在“视图”代码中只需要一个 foreach 循环来打印结果并将它们存储在表中。你们中的任何人都有有用的想法吗? :)
我当前状态的代码如下:
MODEL CODE:
$matches["loandates"] = array();
$matches["loanduedates"] = array();
$matches["itemnames"] = array();
$matches["itemauthors"] = array();
try { // if we do find an item, then we run this query against the database to get a list of all the current loans.
$results = $db->prepare("
SELECT il.loan_date, il.loan_duedate, i.item_name, i.item_author
FROM itemloan il
INNER JOIN libraryitem li
ON il.libraryItem_id = li.libraryItem_id
INNER JOIN item i
ON li.item_id = i.item_id
WHERE il.user_id = ?
ORDER BY il.loan_date asc
");
$results->bindParam(1,$userid); // puts user id value where the placeholder is. First value is character of placeholder, second value is variable we want to bind to placeholder).
$results->execute();
} catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit;
}
while ($row = $results->fetch(PDO::FETCH_ASSOC)) { // we loop through the loans one at a time, and add them to our matches variable
$matches["loandates"][] = $row["loan_date"];
$matches["loanduedates"][] = $row["loan_duedate"];
$matches["itemnames"][] = $row["item_name"];
$matches["itemauthors"][] = $row["item_author"];
}
return $matches;
}
查看代码:
<table id="name">
<?php
foreach($user["itemnames"] as $itemname) {
echo "<tr><td id='radiocell'><input type='radio' name='libraryitemid' id='radio'></td><td class='user'>" . $itemname . "</td></tr>";
}
?>
</table>
<table id="author">
<?php
foreach($user["itemauthors"] as $itemauthor) {
echo "<tr><td class='user'>" . $itemauthor . "</td></tr>";
}
?>
</table>
<table id="date">
<?php
foreach($user["loandates"] as $loandate) {
$time = strtotime($loandate);
$myFormatForView = date("l d F Y", $time);
echo "<tr><td class='user'>" . $myFormatForView . "</td></tr>";
}
?>
</table>
<table id="duedate">
<?php
foreach($user["loanduedates"] as $loanduedate) {
$time = strtotime($loanduedate);
$myFormatForView = date("l d F Y", $time);
echo "<tr><td class='user'>" . $myFormatForView . "</td></tr>";
}
?>
</table>
我最终只想要一个带有一个 foreach 循环的表,而不是四个带有四个 foreach 循环的表。如果你明白我的意思。
如果有人能提供帮助,我将不胜感激!提前致谢!!
问候,
罗伯特,英国伦敦
【问题讨论】:
-
P.S.数据库选择的结果(在模型代码中)都存储在一个名为 $user 的变量中。