我总是扩展 PDO 并添加一些我自己方便的东西。所以首先你像这样扩展:
<?php
//Database class
class db extends Pdo{
public function __construct(){
global $conf;
try
{
parent::__construct('DBTYPE:dbname=DBNAME;host=DBHOST', 'DBUSER', 'DBPASS');
$this->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
throw new myPdoException($e);
}
}
public function quest($queryString){
try
{
$query = $this->query($queryString);
return $query;
}
catch(PDOException $e){
throw new myPdoException($e);
}
}
public function doPrepare($queryString, $param){
try
{
$query = $this->prepare($queryString);
$query->execute($param);
return $query;
}
catch(PDOException $e)
{
throw new myPdoException($e);
}
}
public function doPrepareBind($queryString, $param){
try
{
$query = $this->prepare($queryString);
foreach($param as $par){
switch($par[2]):
case 'int':
$query->bindParam($par[0], $par[1], PDO::PARAM_INT);
break;
case 'str':
$query->bindParam($par[0], $par[1], PDO::PARAM_STR);
break;
case 'blob':
$query->bindParam($par[0], $par[1], PDO::PARAM_LOB);
break;
default:
$query->bindParam($par[0], $par[1], PDO::PARAM_STR);
break;
endswitch;
}
$query->execute();
return $query;
}
catch(PDOException $e)
{
throw new myPdoException($e);
}
}
}
class myPdoException extends PdoException{
private $_debug = DB_DEBUG;
public function __construct($e){
parent::__construct($e);
$this->showException();
}
private function showException(){
if($this->_debug){
echo
"<div id='transparant'><div id='error'><br /><br />" .
$this->message
. "<br /><br /><br /></div></div>";
}
else{
echo "<div id='transparant'><div id='error'><br /><br />
Er is iets mis gegaan, probeer later nog eens.<br />Sorry voor het ongemak.
<br /><br /><br /></div></div>";
}
}
}
?>
您会在第 9 行看到一个父构造函数。您必须添加您的数据库信息来代替大写字母。
请注意,DBTYPE 是您正在使用的数据库服务的类型。可能它只是mysql。
现在这就是我在对一系列字符串进行消毒时使用它的方式:
//first include db class I made above.
$db = new db();
$query = "INSERT INTO `database`.`users` (`id`, `naam`, `email`, `pass`, `key`, `status`) VALUES (NULL, :name, :mail, :pass, '$key', '0')";
$param = array(
array(':name', $_POST['name']),
array(':mail', $_POST['mail']),
array(':pass', $pass_hash)
);
$query = $db->doPrepareBind($query, $param);