有时我会看到关于连接数据库的问题
但是这里有一个疯狂的 idea ;也许我做的都是错的,如果是这样的话;我真的想知道如何使用PHP和PDO正确地连接到MySQL数据库,并使其易于访问.
Here's how I'm doing it:
首先,这里是我的文件 struct (stripped down):
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');
I know there's a better, or more correct, way to include classes, but can't remember what it was. Haven't gotten the time to look into it yet, but I think it was something with 100. something like that...
configure.php
connect.php
我已经把连接放到了一个类上,这样其他类就可以extends这个了.
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();
//
Here I do believe there's room for massive improvement since I recently started learning OOP, and using PDO instead of mysql.
So I've just followed a couple of beginners tutorials and tried out different stuff...
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
-class(extends
-connect_pdo
-class)中,我有一个名为getAreaName
的公共函数,用于处理对数据库的请求
Works like a charm
所以我基本上就是这么做的.
此外,每当我需要从数据库中从类以外的位置获取某些内容时,我只需执行类似的操作:
$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内的一个变量中,我只需要引用它,就可以开始了.它起作用了.我得到了我预期的结果...
但不管怎样,如果你们能告诉我我是不是走得太远了,我会非常感激的.我应该做什么,我可以或应该改变的地方,等等…
我很想学习...