我遵循關於創建一個PDO類的教程,所以我可以更好地理解類和PDO。PHP pdo class getadresses警告和調用成員函數prepare()在非對象
我按照步驟進行了佈置,但最終結果給了我1個警告和一個致命錯誤。
這是錯誤日誌:
Warning: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: Name or service not known on line 24
Fatal error: Call to a member function prepare() on a non-object on line 32
我不是100%肯定此錯誤的原因是什麼,在教程的評論似乎暗示它適用於他們,所以我必須作出一些錯誤在哪裏。
這是我的類函數(見代碼註釋,以瞭解哪些錯誤是)
class DB {
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
private $stmt;
private $dbh;
private $error;
public function __construct(){
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try {
// WARNING occurs here [line 24]
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}// Catch any errors
catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
public function query($query){
// FATAL ERROR [line 34]
$this->stmt = $this->dbh->prepare($query);
}
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute(){
return $this->stmt->execute();
}
public function single(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
}
// Instantiate database.
$database = new DB();
define("DB_HOST", "secret");
define("DB_USER", "secret");
define("DB_PASS", "secret");
define("DB_NAME", "secret");
這也是一個選擇查詢的一個例子,我做測試我的新創建的類:
$database->query('SELECT name FROM users WHERE uid > :id');
$database->bind(':id', 0);
$row = $database->single(); //get the first row selected
echo "<pre>";
print_r($row);
echo "</pre>";
所以我不清楚我的錯誤在哪裏,我的致命錯誤。希望有人能解釋我犯了什麼錯誤,這樣我就能更好地理解。
define("DB_HOST", "secret");
define("DB_USER", "secret");
define("DB_PASS", "secret");
define("DB_NAME", "secret");
// Instantiate database.
$database = new DB();
而且任何代碼之前分配「__construct」方法內所定義的值的屬性,:
$this->host = DB_HOST;
$this->user = DB_USER;
$this->pass = DB_PASS;
$this->dbname = DB_NAME;
希望
哪裏是你提供了適當的憑據構造函數的部分?你還沒有設置這些必要的屬性 – Ghost
你的意思是主機,用戶,密碼和數據庫名稱?如果是這樣 - 它在腳本的底部。 – Sir
你確實已經安裝了mysql,對吧? – ElefantPhace