将所有SQL查询放在一个PHP文件中

时间:2011-08-08 18:48:32

标签: php sql class function

我正在开发一个PHP / Mysql站点。

该网站由静态html模板组成。 使用php require_once

将数据动态填充到这些模板中

例如,这是主页的简化版本

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Home</title>
</head>
<body>
<?php require_once $_SERVER['DOCUMENT_ROOT']."/includes/header.php"; ?>
<?php require_once $_SERVER['DOCUMENT_ROOT']."/includes/connection.php"; ?>
<?php require_once $_SERVER['DOCUMENT_ROOT']."/includes/sql.php"; ?>
<?php require_once $_SERVER['DOCUMENT_ROOT']."/includes/content.php"; ?>
<?php require_once $_SERVER['DOCUMENT_ROOT']."/includes/footer.php"; ?>
</body

页眉和页脚本身是静态的,因此包含在内。 但是为了显示正确的内容,我建立了一个到数据库的连接(connection.php),查询它(sql.php)然后回显它(content.php)。

我对网站上每个页面引用修改后的sql.php的所有其他页面重复此操作。

这一切都有效,但我知道效率不高。

我的问题是如何重构我的文件/代码,以便我最终会得到一个包含我所有SQL查询的文件,以及如何“选择”正确的查询来执行,具体取决于请求它的页面。

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

使用文件中的功能。因此,您可以轻松地调用来自不同文件的函数,例如

$something->this_query();

http://php.net/manual/en/language.functions.php

答案 1 :(得分:0)

如果您需要将所有内容都放在一个文件中,您可以拥有一个2D查询数组,然后只执行所需页面的查询:

$queries = array(
    'home_page' => array( /* insert queries here */ ),
    'contact_page' => array( /* insert queries here */ ),
    'page_Y' => array( /* insert queries here */ ),
    'i_like_turtles' => array( /* insert queries here */ ),
);

然后在page_Y上,您只需foreach($queries['page_Y'] as $query) { /* Execute query */ }

但是,如果您正在寻找更高的效率,最好的方法是在每个单独的页面上列出查询。如果您有数以千计的查询,那么可能值得研究。如果没有,收益将不会很大。