全局变量并减少PHP + MySQL中的数据库访问 [英] global variable and reduce database accesses in PHP+MySQL

查看:68
本文介绍了全局变量并减少PHP + MySQL中的数据库访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是PHP + MySQL的新手,并跟随一个示例来构建网页。

I am new to PHP+MySQL and followed an example to build a web page.

基本上,我的首页读取数据库,检索所有项目,然后页面上的列表。每个项目都有一个指向显示其详细信息的新页面的链接。

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.

列表页面:

//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>

项目页面:

//itemeach.html.php
<html><body>
<h1><?php echo($c1) ?></h1>
<p><?php echo($c2) ?></p>
</body></html>

索引页:

<?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';
?>

我删除了不必要的代码。从第一次加载index.php开始,就检索了$ infos。我想避免再次访问数据库以获得一个特定的项目,因此我正在考虑重用$ infos。但是当我触发 C1时,它变为空。是否可以将$ items保留为全局变量?还是有其他方法可以做到?

I removed the unnecessary code. Since when the first time it loads index.php, $infos is retrieved. I want to avoid accessing to database again to get one specific item, so I am thinking about re-use $infos. But it becomes null when I trigger 'C1'. Is this possible to keep $items as a global variable? or is there other way to do that?

任何帮助将不胜感激!

推荐答案

您可以将检索到的行集存储在$ _SESSION超全局变量中。像:

You could store the retrieved rowset in the $_SESSION superglobal. 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.

这篇关于全局变量并减少PHP + MySQL中的数据库访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆