嘿傢伙我這樣做再次錯誤我敢肯定,但我想實例化PDO數據庫 處理程序從我的班級數據庫從文件class.database.php在class.admin.php的AdminSession 裏面,有些東西對我的依賴注入有些詭異,而且它不是 ,它允許我正確地使用PDO的方法;像fetch(),prepare()etcetra。無法使用PDO方法時,使用數據庫類
的class.database.php文件
class Database
{
public $db; // handle of the db connection
private static $dsn="mysql:host=server2.com;dbname=database";
private static $user="user";
private static $pass="pass";
private static $instance;
public function __construct()
{
$this->db = new PDO(self::$dsn,self::$user,self::$pass,$self::$opts);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
switch($_SERVER['ENVIRONMENT']) {
case 'staging':
self::$dsn="mysql:host=server1.com;dbname=database";
self::$user="user";
self::$pass="pass";
break;
default:
self::$dsn="mysql:host=server2.com;dbname=database";
self::$user="user";
self::$pass="pass";
}
}
public static function getInstance()
{
if(!isset(self::$instance))
{
$object= __CLASS__;
self::$instance=new $object;
}
return self::$instance;
}
}
,這裏是最頂層的我class.admin.php的,那就是拋出一個錯誤的方法。 現在我越來越
PHP致命錯誤的錯誤:調用未定義的方法行230
如果我使用$this->db-prepare($sql)
或
PHP致命錯誤:調用到成員函數prepare()在非對象行上230
如果我使用$db-prepare($sql)
require('library/class.database.php');
class AdminSession {
static $abs_path;
public function __construct(Database $db) {
session_start();
self::$abs_path = dirname(dirname(__FILE__));
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$this->post = $_POST; // filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
if(get_magic_quotes_gpc()) {
//get rid of magic quotes and slashes if present
array_walk_recursive($this->post, array($this, 'stripslash_gpc'));
}
}
$this->get = $_GET; // filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
array_walk_recursive($this->get, array($this, 'urldecode'));
}
// other methods
private function checkDB($username, $password) {
$sql = "SELECT * FROM users WHERE username=:username";
try {
$db = Database::getInstance();
$stmt = $db->prepare($sql);
$stmt->bindParam("username", $username);
$stmt->execute();
$user = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
if($user) {
//general return
if(is_object($user[0]) && md5($user[0]->password) == $password) {
return true;
} else {
return false;
}
} else {
return false;
}
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
}
你會得到什麼錯誤呢? – madfriend 2012-07-19 18:50:57
我添加了一個錯誤,並且還將我的db類稍微修改成了一些更明智的東西。 – ehime 2012-07-19 19:02:15