大家好,我的代码有问题。请参阅下面我当前的代码。我想要实现的是将我的数据库字段(id、name、type)设置为公共属性。
Ex:
public $id;
public $name;
public $type;
我希望你能帮我解决这个问题。:)
错误:
Warning: Missing argument 1 for Animals::__construct() in C:\Program Files\xampp\htdocs\pdo_intro\index.php on line 8
Notice: Undefined variable: dbh in C:\Program Files\xampp\htdocs\pdo_intro\index.php on line 10
Fatal error: Call to a member function prepare() on a non-object in C:\Program Files\xampp\htdocs\pdo_intro\index.php on line 20
我当前的代码
class Animals{
public $db_fields;
private $dbh;
public function __construct($dbh){
$this->dbh = $dbh;
$this->db_fields = $this->get_fields();
foreach($this->db_fields as $field){
$this->$field = "";
}
}
public function get_fields(){
$q = $this->dbh->prepare("DESCRIBE animals");
$q->execute();
$db_fields = $q->fetchAll(PDO::FETCH_COLUMN);
return $db_fields;
}
public function capitalizeType($t){
return ucwords($t);
}
}
/*** 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);
$animal = new Animals($dbh);
/*** echo a message saying we have connected ***/
$sql = "SELECT * FROM animals";
$result = $dbh->query($sql);
while ($r = $result->fetchObject('animals')){
echo $animal->capitalizeType($r->animal_type) . "<br />";
}
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
我试过 __construct($dbh="") 仍然是错误
Fatal error: Call to a member function prepare() on a non-object in C:\Program Files\xampp\htdocs\pdo_intro\index.php on line 20