有时我看到有关连接到数据库的问题。
大多数答案都不是我的方式,或者我可能只是得不到正确的答案。不管怎样,我从来没有想过,因为我做事的方式对我很有效。
但是这里有一个疯狂的想法; 也许我这样做是完全错误的,如果是这样的话; 我真的很想知道如何正确地连接到 MySQL 数据库使用 PHP 和 PDO,并使其易于访问。
我是这么做的:
首先,这是我的文件结构 (脱光):
public_html/
* index.php
* initialize/
-- load.initialize.php
-- configure.php
-- sessions.php
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');
我知道有一个更好的,或者更正确的方法来包含类,但是我不记得是什么了。还没来得及调查但我觉得是 autoload
的问题。诸如此类。
Configure.php
在这里,我基本上只是覆盖了一些 Php.ini属性,并为站点做了一些其他的全局配置
Connect.php
我已经把连接到一个类,这样其他类可以 延伸这一个..。
class connect_pdo
{
protected $dbh;
public function __construct()
{
try {
$db_host = ' '; // hostname
$db_name = ' '; // databasename
$db_user = ' '; // username
$user_pw = ' '; // password
$con = new PDO('mysql:host='.$db_host.'; dbname='.$db_name, $db_user, $user_pw);
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$con->exec("SET CHARACTER SET utf8"); // return all sql requests as UTF-8
}
catch (PDOException $err) {
echo "harmless error message if the connection fails";
$err->getMessage() . "<br/>";
file_put_contents('PDOErrors.txt',$err, FILE_APPEND); // write some details to an error-log outside public_html
die(); // terminate connection
}
}
public function dbh()
{
return $this->dbh;
}
}
# put database handler into a var for easier access
$con = new connect_pdo();
$con = $con->dbh();
//
在这里,我相信自从我最近开始学习 OOP,并使用 PDO 而不是 mysql 以来,还有很大的改进空间。
因此,我只是遵循了一些初学者教程,并尝试了不同的东西...
Sessions.php
除了处理常规会话之外,我还将一些类初始化为下面这样的会话:
if (!isset($_SESSION['sqlQuery'])){
session_start();
$_SESSION['sqlQuery'] = new sqlQuery();
}
这样的话,这个课程可以在任何地方使用。这可能不是一个好的实践(?) ..。
无论如何,这是这种方法允许我在任何地方做的:
echo $_SESSION['sqlQuery']->getAreaName('county',9); // outputs: Aust-Agder (the county name with that id in the database)
在我的 sqlQuery
-同学们(extends
我的 connect_pdo
-同学们)中,我有一个名为 getAreaName
的公共函数,它处理对我的数据库的请求。
我觉得挺不错的。
非常有效
所以我基本上就是这么做的。
此外,每当我需要从数据库中提取不在类中的内容时,我都会做类似的事情:
$id = 123;
$sql = 'SELECT whatever FROM MyTable WHERE id = :id';
$qry = $con->prepare($sql);
$qry -> bindParam(':id', $id, PDO::PARAM_INT);
$qry -> execute();
$get = $qry->fetch(PDO::FETCH_ASSOC);
因为我将连接放入 Connect _ pdo. php中的一个变量中,所以我只需要引用它就可以了。有用。我得到了预期的结果。
But regardless of that; I would really appreciate if you guys could tell me if I'm way off here. What I should do instead, areas I could or should change for improvement etc...
我渴望学习..。