Hello
I am new in oop. I am reading Professional PHP5 of WROX. It uses Postgre as database and i am using Mysql. Whatever, I found a code and changed it to mysql. Here it is :
// class.Widget.php
<?php
class Widget {
private $id;
private $name;
private $description; private $hDB;
private $needsUpdating = false;
public function __construct($widgetID) {
//The widgetID parameter is the primary key of a
//record in the database containing the information
//for this object
//Create a connection handle and store it in a private member variable
$this->hDB = mysql_connect (‘dbname=oop user=root’);
if(! is_resource($this->hD?) {
throw new Exception(‘Unable to connect to the database.’);
}
$sql = “SELECT “name”, “description” FROM widget WHERE widgetid = $widgetID”;
$rs = mysql_query($this->hDB, $sql);
if(! is_resource($rs)) {
throw new Exception(“An error occurred selecting from the database.”);
}
if(! mysql_num_rows($rs)) {
throw new Exception(‘The specified widget does not exist!’);
}
$data = mysql_fetch_array($rs);
$this->id = $widgetID;
$this->name = $data[‘name’];
$this->description = $data[‘description’];
}
public function getName() {
return $this->name;
}
public function getDescription() {
return $this->description;
}
public function setName($name) {
$this->name = $name;
$this->needsUpdating = true;
}
public function setDescription($description) {
$this->description = $description;
$this->needsUpdating = true;
}
public function __destruct() {
if(! $this->needsUpdating) {
return;
}
$sql = ‘UPDATE “widget” SET ‘;
$sql .= “”name” = ‘” . mysql_escape_string($this->name) . “‘, “;
$sql .= “”description” = ‘” . pg_escape_string($this->description) . “‘ “;
$sql .= “WHERE widgetID = ” . $this->id;
$rs = mysql_query($this->hDB, $sql);
if(! is_resource($rs)) {
throw new Exception(‘An error occurred updating the database’);
}
//You’re done with the database. Close the connection handle.
mysql_close($this->hD?;
}
}
?>
And another file called testWidget.php is :
<?php
require_once(‘class.Widget.php’);
try {
$objWidget = new Widget(1);
print “Widget Name: ” . $objWidget->getName() . “<br>n”;
print “Widget Description: ” . $objWidget->getDescription() . “<br>n”;
$objWidget->setName(‘Bar’);
$objWidget->setDescription(‘This is a bartacular widget!’);
} catch (Exception $e) {
die(“There was a problem: ” . $e->getMessage());
}
?>
There is a datebase name oop and the structure is
CREATE TABLE widget (
“widgetid” SERIAL PRIMARY KEY NOT NULL,
“name” varchar(255) NOT NULL,
“description” text
);
INSERT INTO widget (“name”, “description”)
VALUES(‘Foo’, ‘This is a footacular widget!’);
When I run testWidget.php the following error occurs:
“Warning: mysql_connect() [function.mysql-connect]: Unknown MySQL server host ‘dbname=oop user=root’ (11004) in E:apachexampphtdocsLearningclass.Widget.php on line 16
There was a problem: Unable to connect to the database.”.
Can anyone help me?