【发布时间】:2014-06-19 18:07:38
【问题描述】:
编辑:::
所以我有一些我想一起工作的课程。我的前两个建立了与数据库的连接:
dbconn.php
<?php
class dbconn {
protected $dbname;
protected $dbuser;
protected $dbpassword;
protected $dbhost;
protected $connection;
public function __construct($dbhost, $dbname, $dbuser, $dbpass)
{
$this->dbname = $dbname;
$this->dbhost = $dbhost;
$this->dbuser = $dbuser;
$this->dbpass = $dbpass;
$this->connect();
}
public function getConnection()
{
return $this->connection;
}
protected function connect()
{
$this->connection = new PDO("mysql:host={$this->dbhost};dbname={$this->dbname}", $this->dbuser, $this->dbpass);
}
}
?>
dblogin.php
<?php
$db = new DBconn('localhost','phpproject','carl','pdt1848?')
?>
我的其他班级正在尝试编辑数据库中的项目。我试图通过这个类的 __construct 链接数据库连接类,我只是在做这一切显然都是错误的。
编辑啤酒.php
<?php
class BeerEditor
{
protected $dbconn;
function __construct($dbconn){
$this->dbconn = $dbconn;
}
function addBeer(Beer $beerObj){
//making connection to db here
$conn = $this->dbconn->getConnection();
$stmt = $conn->prepare("INSERT INTO beers (beer_name, beer_type, beer_abv, beer_rating) VALUES (:beer_name, :beer_type, :beer_abv, :beer_rating)");
$stmt->bindParam(':beer_name', $beerObj->getBeerName());
$stmt->bindParam(':beer_type', $beerObj->getBeerType());
$stmt->bindParam(':beer_abv', $beerObj->getBeerABV());
$stmt->bindParam(':beer_rating', $beerObj->getBeerRating());
$result = $stmt->execute();
if($result === false){
var_dump($conn->errorCode());
}
return $result;
}
function listBeers(){
$conn = $this->dbconn->getConnection();
$result = $conn->query('SELECT * FROM beers');
$result->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'beers');
$beers = $result->fetchAll();
return $beers;
}
}
?>
【问题讨论】:
-
错误非常具体。它说 $dbconn 没有定义。它应该来自哪里?
-
您班级中的变量
$dbconn是您班级的私有变量。您页面中的变量$dbconn是一个完全不同的变量。你需要给它一个值in your page 以便将它传递给你的类。您不能依赖类中的变量提供要传递给类的值以分配给类中的变量,该变量提供要传递给类的值...