我们有一个从MySQL数据库中提取的日期列表。这部分非常简单,工作正常,执行$查询,逐步执行数组,找到符合条件的那些,回显一些HTML代码和日期本身。
我们希望解决的问题是此列表显示在网页上的三个不同位置。每次出现时,运行php代码,进行数据库查询并回显结果。
我想知道的是,如果有一种方法可以在开头创建一个php变量,然后简单地在所有三个位置回显该变量,而不是运行三次代码。
我尝试过简单使用的noob想法:
$date = ( ...all the php query / echo code... );
and
$date = { ...all the php query / echo code... };
以及那里的排列。但无济于事。
答案 0 :(得分:1)
是的,您可以将它存储在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 />";
}
.=
追加(连接)字符串。
奖励:如果您有大量数据,那可能会更好w.r.t.首先收集所有行,然后在单个操作中将它们连接成一个字符串的效率。你可以这样做:
$rows = array();
while($tourtime = fetch_result_from_db(...)){
$rows[] = "<span class=\"dates\">". date ("j F Y", $tourtime) . "</span><br />";
}
$date = implode($rows);
答案 1 :(得分:0)
是的,您可以在使用变量之前为变量赋值。随意做。
如果3个点具有不同的参数,则应将变量创建为类似模板的样式。
// beginning of the code
$statementTemplate = "select * from x where a=8 and b<9 order by #";
//... some code...
// point 1
$statement = str_replace("#","name",$statementTemplate);
// perform statement
//... some code...
// point 2
$statement = str_replace("#","name desc",$statementTemplate);
// perform statement
//... some code...
// point 3
$statement = str_replace("#","lastmodify",$statementTemplate);
// perform statement
不要害怕,程序可以做任何事情!