我不时会看到有关连接数据库的问题.
大多数答案不是我这样做的方式,或者我可能没有正确得到答案.无论如何; 我从来没有想过这个,因为我这样做对我有用.
但这是一个疯狂的想法; 也许我这样做是错的,如果是这样的话; 我真的想知道如何使用PHP和PDO正确连接到MySQL数据库并使其易于访问.
我是这样做的:
首先,这是我的文件结构(剥离):
public_html/
* index.php
* initialize/
-- load.initialize.php
-- configure.php
-- sessions.php
Run Code Online (Sandbox Code Playgroud)
index.php
在最顶端,我有require('initialize/load.initialize.php');.
load.initialize.php
# site configurations
require('configure.php');
# connect to database
require('root/somewhere/connect.php'); // this file is placed outside of public_html for better security.
# include classes
foreach (glob('assets/classes/*.class.php') as $class_filename){
include($class_filename);
}
# include functions
foreach (glob('assets/functions/*.func.php') as $func_filename){
include($func_filename);
}
# handle sessions
require('sessions.php');
Run Code Online (Sandbox Code Playgroud)
我知道有更好或更正确的方法来包含类,但不记得它是什么.还没有时间去研究它,但我认为这是有道理的autoload.类似的东西......
configure.php
这里我基本上只是覆盖一些php.ini -properties并为该站点做一些其他的全局配置
connect.php
我把连接放到一个类上,所以其他类可以扩展这个...
class …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个分页类并使用类外的变量.
但它给了我一个致命的错误"调用非对象的成员函数查询()".
这是索引文件:
$db = new DB_MySQL("localhost", "root", "", "test"); // connect to the database
include_once("pagi.php");
$pagination = new pagi();
$records = $pagination->get_records("SELECT * FROM `table`");
Run Code Online (Sandbox Code Playgroud)
这是pagi.php文件:
class pagi {
public function get_records($q) {
$x = $db->query($q);
return $db->fetch($x);
}
}
Run Code Online (Sandbox Code Playgroud)
是否可以在类的类外部使用此变量,而无需在类中创建新的变量?