gpt4 book ai didi

php - 为 mysql 创建一个 php 变量

转载 作者:行者123 更新时间:2023-11-29 14:38:44 24 4
gpt4 key购买 nike

我们有一个从 MySQL 数据库中提取的日期列表。这部分非常简单并且工作得很好,执行 $query,单步遍历数组,找到满足条件的那些,回显一些 html 代码和日期本身。

我们希望解决的问题是该列表出现在网页上的三个不同位置。每次出现时,都会运行 php 代码,进行数据库查询并回显结果。

我想知道是否有一种方法可以在开始时创建一个 php 变量,然后简单地在所有三个位置回显该变量,而不是运行代码三次。

我尝试过简单使用的菜鸟想法:

$date = ( ...all the php query / echo code... );
and
$date = { ...all the php query / echo code... };

以及其中的排列。但没有效果。

最佳答案

是的,您可以将其存储在 php 文件顶部的变量中:

// query ...
// but don't echo, store in a string
$date = 'this contains what is supposed to be echoed later on.';

然后:

echo $date;

还有其他地方:

echo $date;
<小时/>

关于您的评论:

$date = ''; // this will hold all dates
while($tourtime = fetch_result_from_db(...)){ // 'the loop', whatever yours look like
// instead of echoing, append to the string $date
$date .= "<span class=\"dates\">". date ("j F Y", $tourtime) . "</span><br />";
}

.= 追加(连接)字符串。

<小时/>

奖励:如果您有大量数据,可能会更好。首先收集所有行,然后在单个操作中将它们连接成一个字符串的效率。你可以这样做:

$rows = array();
while($tourtime = fetch_result_from_db(...)){
$rows[] = "<span class=\"dates\">". date ("j F Y", $tourtime) . "</span><br />";
}
$date = implode($rows);

关于php - 为 mysql 创建一个 php 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8445699/

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