gpt4 book ai didi

PHP foreach 输出所有内容四次(mysql、sql、数据库管理)

转载 作者:行者123 更新时间:2023-11-30 22:45:22 25 4
gpt4 key购买 nike

我这里有一些代码,我觉得可以提高效率。我一直在构建一个图书馆目录数据库,我正在寻找一种方法来将从 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 循环。如果你明白我的意思。

如果有人能提供帮助,我将不胜感激!提前致谢!!

问候,

罗伯特,英国伦敦

最佳答案

 $matches[] = array("loandates" => $row["loan_date"],
"loanduedates" => $row["loan_duedate"],
"itemnames" => $row["item_name"],
"itemauthors" => $row["item_author"]);

现在你有了一个数组,你可以用一个 foreach 来显示它。

foreach($matches as $match) {
echo $match['loandates'] . '</td><td>' . $match['loan_duedate'] ...

关于PHP foreach 输出所有内容四次(mysql、sql、数据库管理),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29799503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com