[英]global variable and reduce database accesses in PHP+MySQL
I am new to PHP+MySQL and followed an example to build a web page. 我是PHP + MySQL的新手,并按照示例构建了一个网页。
Basically, my front page reads the databas, retrieves all the items, and lists on the page. 基本上,我的首页读取数据库,检索所有项目,并在页面上列出。 Each item has a link to a new page showing its details.
每个项目都有一个指向显示其详细信息的新页面的链接。
the list page: 列表页面:
//itemlist.html.php
<html><body>
<ul>
<?php foreach ($items as $item): ?>
<li><a href="?C1=<?php echo($item['c1']); ?>">
<?php echo($item['c1']); ?></a></li>
<?php endforeach; ?>
</ul>
</body></html>
the item page: 项目页面:
//itemeach.html.php
<html><body>
<h1><?php echo($c1) ?></h1>
<p><?php echo($c2) ?></p>
</body></html>
the index page: 索引页:
<?php
if (isset($_GET['C1']))
{
/*
I want to reuse $iteminfos and get value for $c1 and $c2
*/
include 'itemeach.html.php';
exit();
}
$result = mysqli_query($link, 'SELECT * FROM TB');
while ($row = mysqli_fetch_array($result))
{
$items[] = array('c1' => $row['c1'], 'c2' => $row['c2']);
}
include 'itemlist.html.php';
?>
I removed the unnecessary code. 我删除了不必要的代码。 Since when the first time it loads index.php, $infos is retrieved.
从第一次加载index.php开始,就检索了$ infos。 I want to avoid accessing to database again to get one specific item, so I am thinking about re-use $infos.
我想避免再次访问数据库以获得一个特定的项目,所以我正在考虑重用$ infos。 But it becomes null when I trigger 'C1'.
但是当我触发“ C1”时,它变为空。 Is this possible to keep $items as a global variable?
是否可以将$ items保留为全局变量? or is there other way to do that?
还是有其他方法可以做到这一点?
Any help would be greatly appreciated! 任何帮助将不胜感激!
You could store the retrieved rowset in the $_SESSION superglobal. 您可以将检索到的行集存储在$ _SESSION超全局变量中。 Like:
喜欢:
if (empty($_SESSION['items']) {
$result = mysqli_query($link, 'SELECT * FROM TB');
while ($row = mysqli_fetch_array($result)) {
$rowData[] = array('c1' => $row['c1'], 'c2' => $row['c2']);
}
$_SESSION['items'] = $rowData;
}
$items = $_SESSION['items'];
But yeah what Dagon said is true. 但是,是的,达贡所说的是真的。
Just move the query and while loop to above the if (isset($_GET['C1'])) line, this will make $items available to the itemeach.html.php script. 只需将查询和while循环移至if(isset($ _ GET ['C1']))行上方,这将使$ items可用于itemeach.html.php脚本。 If you could post the contents of itemeach.html.php we can help you further.
如果您可以发布itemeach.html.php的内容,我们可以为您提供进一步的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.