2
嗨,大家好,我的代碼有問題。與__construct()我得到致命錯誤:調用成員函數prepare()在一個非對象,但沒有它我的代碼正在工作。調用成員函數prepare()在PDO中的非對象
class Animals{
public $db_fields;
public function __construct(){
$this->db_fields = $this->get_fields();
foreach($this->db_fields as $field){
$this->$field = "";
}
public function get_fields(){
global $dbh;
$q = $dbh->prepare("DESCRIBE animals");
$q->execute();
$db_fields = $q->fetchAll(PDO::FETCH_COLUMN);
return $db_fields;
}
}
$f = new Animals();
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'root';
/*** mysql password ***/
$password = '';
/*** mysql database***/
$dbname = 'animals';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database <br />';
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
我只想讓我的字段(animal_id,animal_type,animal_name)上班一樣
public $animal_id;
public $animal_type;
public $animal_name;
刪除'$ dbh = null;',否則就是覆蓋PDO對象。 – air4x