EDIT:::
So I have classes that I would like to work together. My first two establish a connection to the database:
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?')
?>
My other class is trying to edit items from the database. I tried to link the db connection classes throught the __construct of this class, I'm just going about this all wrong apparently.
editbeers.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;
}
}
?>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…