I am trying to learn the basics of OOP PHP however I am stuck at this part:
<?php
class Database {
private $dbuser;
private $dbpass;
private $dbhost;
private $database;
private $link;
private $connection;
function __construct($dbhost, $dbuser, $dbpass, $database) {
$this->dbhost = $dbhost;
$this->dbuser = $dbuser;
$this->dbpass = $dbpass;
$this->database = $database;
$this->link = mysql_connect($this->dbhost, $this->dbuser, $this->dbpass);
$this->link = mysql_select_db($this->database);
return true;
}
function NewQuery($query) {
$execute = mysql_query($query);
if (!$execute) die('Invalid query: ' . mysql_error());
return $execute;
}
function __destruct() {
mysql_close($this->link);
}
}
At my index page I get this error on mysql_close. Is there anything I could do to fix it on __destruct() class?
Warning: mysql_close() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\projects\oop\classes\database.php on line 33
If you look at the documentation for mysql_select_db()
the first thing you see is the big red box that says you shouldn't use mysql_
functions anymore.
That out of the way, the page also says that the function returns true
on success and false
on error. That means you're overwriting the variable that holds the connection ($this->link
) with a boolean, which causes the error later when you try to close it.
The simple solution is to not store the return value of database selection anywhere, or to use a separate variable for it.
Let's go on with PDO
!
<?php
class Database {
private $con;
public function __construct($dbname, $dbhost, $dbuser, $dbpass) {
$this->con = new PDO(
sprintf('mysql:dbname=%s;host=%s;charset=utf8',
$dbname,
$dbhost
),
$dbuser,
$dbpass,
array(
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
)
);
}
function execute($sql, $params = array()) {
$stmt = $this->con->prepare($sql);
foreach ($params as $key => $v) {
list($value, $type) = is_array($v) ?
$v :
array($v, PDO::PARAM_STR)
;
$stmt->bindValue($key, $value, $type);
}
$stmt->execute();
return $stmt;
}
}
Example usage:
$_POST['age'] = '15'; // user input
try {
if (!isset($_POST['age']) || !is_string($age = $_POST['age'])) {
throw new Exception('parameter $_POST["age"] required');
}
$db = new Database('testdb', 'localhost', 'root', '');
$params = array(
':age' => array(
$age,
PDO::PARAM_INT,
)
);
$sql = 'SELECT COUNT(*) FROM people WHERE age = :age';
printf("The number of %d years old people is %d
",
$age,
$db->execute($sql, $params)->fetchColumn()
);
$sql = 'SELECT * FROM people WHERE age = :age';
foreach ($db->execute($sql, $params) as $user) {
echo "
";
printf("Name : %s
", $user->name);
printf("Age : %d
", $user->age);
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}