Database connection through class - php

i want to crete a class that will contain various general variables and functions to be used throughout the website. One of these things will be a database connection. I am trying the following code:
class Sys {
public $dbc = new mysqli('localhost', 'user', 'pass', 'db');
$dbc->query("SET NAMES 'utf8' COLLATE 'utf8_unicode_ci'");
}
$system = new Sys;
It is giving me a syntax error in the first line of the class... What am i doing wrong?
Thanks

you should do things like this in the constructor. You can only set primitives in the initial declaration. Also you need braces when creating the object.
class Sys {
private $dbc;
private $someInteger = 4; // you can do this
private $someArray = array(); // and this.
public function __construct()
{
$this->dbc = new mysqli('localhost', 'user', 'pass', 'db');
$this->dbc->query("SET NAMES 'utf8' COLLATE 'utf8_unicode_ci'");
}
public function getDbc()
{
return $this->dbc;
}
}
$system = new Sys();
//$system->getDbc()->soSomethingWithMyDb();
i would advise you to read up on using objects: http://php.net/manual/en/language.types.object.php

You should just declare a public $dbc.
And then have a constructor function function __construct() { ...... } where you initialize it/ set it up.
class Sys {
public $dbc;
function __construct() {
$this->dbc = new mysqli('localhost', 'user', 'pass', 'db');
$this->dbc->query("SET NAMES 'utf8' COLLATE 'utf8_unicode_ci'");
}
}
$system = new Sys;

class Sys {
var $mysqli;
function DB($database,$server,$user,$pass) {
$this->mysqli = mysqli_connect($server, $user, $pass, $base) or die('Server connection not possible. '. mysqli_connect_error());
}
}
include("db.class.mysqli.php"); // db handler class
// Open the base (construct the object):
$db = new Sys(DB_NAME, SERVER_NAME, USER_NAME, PASSWORD);
This is how I do it

check out the use of magic methods http://php.net/manual/en/language.oop5.magic.php in php - as mentioned above the __construct method is needed for your class to work. Below is an example from Peter Lavin's book Object Oriented PHP http://objectorientedphp.com/ in chapter 9.
class MySQLConnect {
// Data Members
private $connection;
private static $instances = 0;
// Constructor
public function __construct($hostname, $username, $password) {
if(MySQLConnect::$instances == 0) {
$this->connection = new mysqli($hostname, $username, $password);
// Check for Errors then report them
if ($this->connection->connect_error) {
die("Connect Error ($this->connection->connect_errno) $this->connection->connect_error");
}
// Set the Class variable $instances to 1
MySQLConnect::$instances = 1;
} else {
$msg = "There's another instance the MySQLConnect Class with a connect open already. Close it";
die($msg);
}
}
}

Try this:
$db = new DB;
$link = $db->connect()->getLink();
class DB {
public $connection = array();
public function __construct() {
return $this;
}
public function connect($host=null, $user=null, $pass=null, $database=null) {
$this->connection = new Connection($host, $user, $pass, $database);
$this->connection->connect();
$this->link = $this->connection->getLink();
if ($this->connection->ping()) {
if (!is_null($database)) {
if (!$this->connection->databaseConnect($database)) {
throw new\Exception('Unable to connect to the server.');
}
}
}else{
throw new \Exception('Unable to connect to the server.');
}
return $this;
}
public function getLink() {
return $this->link;
}
}
class Connection {
protected $chost='localhost';
protected $cuser='guest';
protected $cpass='password';
protected $cdatabase='PROFORDABLE';
function __construct($host=null, $user=null, $pass=null, $database=null) {
$host = !is_null($host) ? $host : $this->chost;
$user = !is_null($user) ? $user : $this->cuser;
$password = !is_null($pass) ? $pass : $this->cpass;
$database = !is_null($database) ? $database : $this->cdatabase;
$this->set('host', $host)->set('user', $user)->set('password', $password)->set('database', $database);
return $this;
}
public function connect() {
$link = mysqli_connect($this->host->getHost(), $this->user->getUser(), $this->password->getPassword());
if (!is_object($link)) {
throw new \Exception("An error has occurred while connecting to the server.");
}
$this->link = $link;
}
public function databaseConnect($database) {
if (!mysqli_select_db($this->getLink(), $database)) {
throw new \Exception("Unable to select the database.");
}
}
public function getLink() {
return $this->link;
}
public function ping() {
if (mysqli_ping($this->link)) {
return TRUE;
}
return FALSE;
}
public function set($name, $param) {
if (!isset($name) || !isset($param)) return $this;
$class = __NAMESPACE__.'\\'.ucwords($name);
$this->$name = new $class($param);
return $this;
}
public function get($name) {
$getfunc = 'get'.ucwords($name);
return $this->$name->$getFunc();
}
}
class Host {
public function __construct($host) {
$this->setHost($host);
}
public function setHost($host) {
$this->host = $host;
}
public function getHost() {
return $this->host;
}
}
class User {
public function __construct($user) {
$this->setUser($user);
}
public function setUser($user) {
$this->user = $user;
}
public function getUser() {
return $this->user;
}
}
class Password {
public function __construct($password) {
$this->setPassword($password);
}
public function setPassword($password) {
$this->password = $password;
}
public function getPassword() {
return $this->password;
}
public function sha($value) {
return sha1($value);
}
}
class guestPassword extends Password {
const PASSWORD='password';
public function __construct() {
return PASSWORD;
}
}
class Database {
public function __construct($database) {
$this->setDatabase($database);
}
public function setDatabase($database) {
$this->database = $database;
}
public function getDatabase() {
return $this->database;
}
}
class Query {
}

//Create mysql.php and paste following code
<?php
class MySQL {
private $set_host;
private $set_username;
private $set_password;
private $set_database;
public function __Construct($set_host, $set_username, $set_password) {
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
$con = mysql_connect($this->host, $this->username, $this->password);
if (!$con) {
die("Couldn't connect to the server");
}
}
//end of __construct
//connect to database
public function Database($set_database) {
$this->database = $set_database;
mysql_query("set character_set_server='utf8'");
mysql_query("set names 'utf8'");
mysql_select_db($this->database) or die("Unable to select database");
}
//fetch data from any table
public function fetch_data($sql) {
$this->sql = $sql;
$query = mysql_query($this->sql);
$result = array();
while ($record = mysql_fetch_array($query)) {
$result[] = $record;
}
return $result;
}
//fetch all columns from any table to be used for INSERT INTO.
public function get_all_columns($table_name) {
$this->table_name = $table_name;
$sql = "SHOW COLUMNS FROM $this->table_name";
$result = mysql_query($sql);
while ($record = mysql_fetch_array($result)) {
$fields[] = $record['0'];
}
$val = '';
foreach ($fields as $value) {
$val .= $value . ',';
}
$vals = rtrim($val, ',');
return $vals;
}
//insert data to any table by $_POST or set of variables separated by ,
public function insert_data($tbl_name, $tbl_value) {
$this->tbl_name = $tbl_name;
$this->tbl_value = $tbl_value;
//use mysql_real_escape_string($tbl_value) to clean & insert data.
$this->tbl_col = $this->get_all_columns($this->tbl_name);
$sql = "INSERT INTO $this->tbl_name ($this->tbl_col) VALUES ($this->tbl_value)";
$query_result = mysql_query($sql);
}
//end of insert data
public function delete_data($del_id, $table_name) {
$this->del_id = $del_id;
$this->table_name = $table_name;
if (isset($this->del_id) && is_numeric($this->del_id) && !empty($this->del_id)) {
$sql = "DELETE FROM $this->table_name WHERE id=$this->del_id LIMIT 1";
$del_result = mysql_query($sql);
$aff_row = mysql_affected_rows();
return $aff_row;
}
}
}
// class ends here
//call class to connect to server and db as well.
$connect = new MySQL('localhost', 'root', '');
$connect->Database('db_name');
?>
//include file mysql.php and call your class object as :
//fetching data from any table use :
$variable = $connect->fetch_data("SELECT * FROM table_name");
for($i=0;$i<count($variable);$i++){
$result = $variable[$i]['col_name'];
}
//insert INTO values in any table
$result = $connect->insert_data($tbl_name, $tbl_value);
if($result)
echo 'inserted';
else{
echo 'failed';
}
//delete record from any table
$result = $connect->delete_data($del_id, $table_name)

You can use a wonderful class ezSQL

Related

How get Id user with PDO and Class [duplicate]

This question already has an answer here:
How to use PDO connection in other classes?
(1 answer)
Closed 2 years ago.
I got this PDO database class
class clsDatabase{
// db settings
private $host = 'localhost';
private $user = 'test';
private $dbname = 'test';
private $pass = 'test1';
private $dbh;
private $error;
public function __construct(){
// Set DSN
$dsn = 'mysql: host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8'
);
// Create a new PDO instanace
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
// Catch any errors
catch(PDOException $e){
$this->error = $e->getMessage();
echo $this->error;
exit;
}
}
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
}
I try to seperate my code in different classes, for example i got a clsDBUser which is connected to the clsUserController. I do this so i know what class uses what database code. My clsDBUser class looks like this
class clsDBUser extends clsDatabase {
// construct
public function __construct() {
parent::__construct();
}
// get users
public function getUsers($users_id){
$query = "
SELECT
email
FROM
users
WHERE
users_id = :users_id
";
$this->query($query);
$this->bind(':users_id', $users_id);
if($row = $this->single()){
$this->close();
return $row;
}
$this->close();
return false;
}
}
I am wondering if this is the way to go or am i creating a new database connection in every class right now? Because normally in PHP4 (yes i know old) i can't recognize i had to make a new database connection every time.
Do i need to improve this, how do i need to improve this?
You should take the road shown in the mr.void's answer. In short:
get rid of clsDatabase.
Create an instance of PDO.
pass it into clsDBLogin's property like it shown in mr.void's answer.
Then use this pdo instance in the form of $this->db->prepare() and so on
So it should be like
class clsDBLogin
{
public function __construct($db)
{
$this->db = $db;
}
public function validateLogin($email)
{
$email = trim($email);
// Check user in db to start verification
$query = 'SELECT * FROM users u, users_info ui
WHERE u.users_id = ui.users_id AND u.email = ?';
$stmt = $this->db->prepare($query);
$stmt->execute([$email]);
return $stmt->fetch();
}
}
$dsn = 'mysql: host=localhost;dbname=test;charset=utf8';
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
);
// Create a new PDO instanace
$pdo = new PDO($dsn, $this->user, $this->pass, $options);
$DBLogin = new clsDBLogin($pdo);
$user = $DBLogin->validateLogin($email);
Hey i would do Something like this
class DB {
// connectionStuff goes Here
}
class Model {
private $db
public function __construct($db) {
$this->db = $db;
}
}
Use:
$db = new DB("your connection stuff goes here");
$model = new Model($db);
$userModel = new UserModel($db);
$anotherModel = new AnotherModel($db);
Rebuild:
clsDB class with connection stuff only
class clsDB{
// db settings
private $host = 'localhost';
private $user = 'test';
private $dbname = 'test';
private $pass = 'test';
private $dbh;
private $error;
public function __construct(){
// Set DSN
$dsn = 'mysql: host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8'
);
// Create a new PDO instanace
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
// Catch any errors
catch(PDOException $e){
$this->error = $e->getMessage();
echo $this->error;
exit;
}
}
}
clsDBLogin:
class clsDBLogin{
private $db;
public function __construct($db) {
$this->db = $db;
}
}
In index.php i do:
$clsDB = new clsDB();
$clsDBLogin = new clsDBLogin($clsDB);
In clsDBLogin i would do:
public function validateLogin($email){
$email = str_replace(' ', '', $email);
$email = strtolower($email);
// Check user in db to start verification
$query = '
SELECT
u.*, ui.*
FROM
users as u,
users_info as ui
WHERE
u.users_id = ui.users_id
AND
u.email = :email
';
$this->db->prepare($query);
$this->db->bindValue(':email', $email, PDO::PARAM_STR);
if($this->db->execute()){
if($row = $this->db->fetch(PDO::FETCH_ASSOC)){
return $row;
}
}
}
There are three layer here:
database connector: you can use pure PDO for this or a database abstraction layer library (Doctrine DBAL)
repository of entities: in other words, some kind of ORM. Doctrine provides advanced ORM functionality. Of course, you can write your own lightweight solution.
entity: can be a simple CRUD, an ActiveRecord or any other object representation of a logical record.
When we do this manually... First, don't extend these from each other. Generally: never extend a different layer from an other. Use Dependency Injection (DI) instead.
It's a very simple case of DI when you pass all the specific information (dependencies) as constructor parameters. My active-object-like example Entity just knows how an entity should be behave in general (at a key in a repository). For simplicity, I use raw SQL.
Repository class:
class Repository {
private $oPDO;
private $tableName;
private $keyFieldName;
public function __construct($oPDO, $tableName, $keyFieldName) {
$this->oPDO = $oPDO;
$this->tableName = $tableName;
$this->keyFieldName = $keyFieldName;
}
public function getPDO() {
return $this->oPDO;
}
public function getTableName() {
return $this->tableName;
}
public function getKeyFieldName() {
return $this->keyFieldName;
}
public function getEntity($id) {
return new Entity($this, $id);
}
public function createEntity() {
return new Entity($this, null);
}
}
Entity class:
class Entity implements ArrayAccess {
private $oRepository;
private $id;
private $record = null;
public function __construct($oRepository, $id) {
$this->oRepository = $oRepository;
$this->id = $id;
}
public function load($reload = false) {
if (!$this->record && !$this->id) {
return false;
}
if (!$reload && !is_null($this->record)) {
return true;
}
$quotedTableName = $this->quoteIdentifier($this->oRepository->getTableName());
$quotedKeyFieldName = $this->quoteIdentifier($this->oRepository->getKeyFieldName());
$selectSql = "SELECT * FROM {$quotedTableName} WHERE {$quotedKeyFieldName} = ?";
$oStatement = $this->oRepository->getPDO()->prepare($selectSql);
$this->bindParam($oStatement, 1, $this->id);
$oStatement->execute();
$result = $oStatement->fetch(PDO::FETCH_ASSOC);
if ($result === false || is_null($result)) {
return false;
}
$this->record = $result;
return true;
}
public function save() {
$oPDO = $this->oRepository->getPDO();
$tableName = $this->oRepository->getTableName();
$keyFieldName = $this->oRepository->getKeyFieldName();
$quotedTableName = $this->quoteIdentifier($tableName);
$quotedKeyFieldName = $this->quoteIdentifier($keyFieldName);
if (is_null($this->id)) {
$insertSql = "INSERT INTO {$quotedTableName} (";
$insertSql .= implode(", ", array_map([$this, "quoteIdentifier"], array_keys($this->record)));
$insertSql .= ") VALUES (";
$insertSql .= implode(", ", array_fill(0, count($this->record), "?"));
$insertSql .= ")";
$oStatement = $oPDO->prepare($insertSql);
$p = 1;
foreach ($this->record as $fieldName => $value) {
$this->bindParam($oStatement, $p, $value);
$p++;
}
if ($oStatement->execute()) {
$this->id = $oPDO->lastInsertId();
return true;
} else {
return false;
}
} else {
$updateSql = "UPDATE {$quotedTableName} SET ";
$updateSql .= implode(" = ?, ", array_map([$this, "quoteIdentifier"], array_keys($this->record)));
$updateSql .= " = ? WHERE {$quotedKeyFieldName} = ?";
$oStatement = $oPDO->prepare($updateSql);
$p = 1;
foreach ($this->record as $fieldName => $value) {
$this->bindParam($oStatement, $p, $value);
$p++;
}
$this->bindParam($oStatement, $p, $this->id);
if ($oStatement->execute()) {
if (isset($this->record[$keyFieldName])) {
$this->id = $this->record[$keyFieldName];
}
return true;
} else {
return false;
}
}
}
public function isExisting($reload = false) {
if (!$this->record && !$this->id) {
return false;
}
if (!$reload && !is_null($this->record)) {
return true;
}
$quotedTableName = $this->quoteIdentifier($this->oRepository->getTableName());
$quotedKeyFieldName = $this->quoteIdentifier($this->oRepository->getKeyFieldName());
$selectSql = "SELECT 1 FROM {$quotedTableName} WHERE {$quotedKeyFieldName} = ?";
$oStatement = $this->oRepository->getPDO()->prepare($selectSql);
$oStatement->bindParam(1, $this->id);
$oStatement->execute();
$result = $oStatement->fetch(PDO::FETCH_ASSOC);
if ($result === false || is_null($result)) {
return false;
}
return true;
}
public function getId() {
return $this->id;
}
public function getRecord() {
$this->load();
return $this->record;
}
public function offsetExists($offset) {
$this->load();
return isset($this->record[$offset]);
}
public function offsetGet($offset) {
$this->load();
return $this->record[$offset];
}
public function offsetSet($offset, $value) {
$this->load();
$this->record[$offset] = $value;
}
public function offsetUnset($offset) {
$this->load();
$this->record[$offset] = null;
}
private function quoteIdentifier($name) {
return "`" . str_replace("`", "``", $name) . "`";
}
private function bindParam($oStatement, $key, $value) {
$oStatement->bindParam($key, $value);
}
}
Usage:
$oRepo = new Repository($oPDO, "user", "user_id");
var_dump($oRepo->getEntity(2345235)->isExisting());
$oSameUser = $oRepo->getEntity(1);
var_dump($oSameUser->isExisting());
var_dump($oSameUser->getRecord());
$oNewUser = $oRepo->createEntity();
$oNewUser["username"] = "smith.john";
$oNewUser["password"] = password_hash("ihatesingletons", PASSWORD_DEFAULT);
$oNewUser["name"] = "John Smith";
$oNewUser->save();
$oNewUser["name"] = "John Jack Smith";
$oNewUser->save();
Of course, you can extend a MoreConcreteRepository from Repository and MoreConcreteEntity from Entity with specific behavior.
Simply don't extend an entity (clsDBUser) from a connection class (clsDatabase).
Use a singleton (or something more advanced pattern) for clsDatabase.
For example:
class clsDatabase {
static private $instance = null;
// some other private fields
private function __construct(/* parameters*/) {
// do it
}
public static function instance() {
if (is_null(self::$instance)) {
self::$instance = new self(/* pass any parameters */);
}
return self::$instance;
}
public function queryRow($query) {
$oStatement = $this->dbh->prepare($query);
// ...
return $row;
}
}
class clsDBUser {
public function getUser($id) {
$query = "...";
return $clsDatabase::instance()->queryRow($query);
}
}

Errors while trying to load data from MySql

I am working/learning how to mvc a project structure. I have a database connector, a registry class, a model and an application model. I have all these in one place to check it working. The problem is I get these three errors when I execute.
<?php
class db
{
protected $conn;
protected $host, $username, $password, $database;
public function __construct($host, $username, $password, $database)
{
$this->conn = new mysqli($host, $username, $password, $database)
OR die("There was a problem connecting to the database");
return true;
}
public function query($sql)
{
$result = $this->conn->query($sql);
if (!$result) {
die('Invalid query:');
}
return $result;
}
public function escape($value)
{
return $this->conn->real_escape_string($value);
}
public function countAffected()
{
return $this->conn->affected_rows;
}
public function getLastId()
{
return $this->conn->insert_id;
}
public function __destruct()
{
$this->conn->close()
OR die("Problem disconnecting from the database");
}
}
final class registry
{
private $data = array();
public function get($key)
{
return (isset($this->data[$key]) ? $this->data[$key] : null);
}
public function set($key, $value)
{
$this->data[$key] = $value;
}
public function has($key)
{
return isset($this->data[$key]);
}
}
abstract class Model
{
protected $registry;
public function __construct($registry)
{
$this->registry = $registry; // Undefined variable: registry
}
public function __get($key)
{
return $this->registry->get($key);
}
public function __set($key, $value)
{
$this->registry->set($key, $value);
}
}
class MemberModel extends Model
{
public function getMember()
{
$result = $this->query("SELECT * FROM members"); //Call to undefined method MemberModel::query()
return $result;
}
}
// DB
define('DB_HOSTNAME', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'pcaframework');
$registry = new registry();
// Database
$db = new db(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
$registry->set('db', $db);
$membermodel = new MemberModel(); //Missing argument 1 for Model::__construct()
$allMembers = $membermodel->getMember();
while ($row = mysqli_fetch_assoc($allMembers)) {
echo "First Name: " . $row['name'] . "<br />";
echo "Last Name: " . $row['email'] . "<br />";
echo "<hr />";
}
Missing argument 1 for Model::__construct(), called on $membermodel = new MemberModel();
Undefined variable: registry
Call to undefined method MemberModel::query()
I have commented the error in the code to mark exactly where the error occurs.
Solution to:
$result = $this->query("SELECT * FROM members"); //Call to undefined method MemberModel::query()
Replace with:
$result = $this->conn->query("SELECT * FROM members");
You just forget the "->conn->".
Solution to:
$this->registry = $registry; // Undefined variable: registry
And
$membermodel = new MemberModel(); //Missing argument 1 for Model::__construct()
Just replace this last with the $registry var as a parameter to the new class:
$membermodel = new MemberModel($registry);
You're calling the constructor, that needs a parameter, but you're not refering that parameter.

Why Warning: mysqli_query(): Couldn't fetch mysqli?

I don't understand why I remove code in line 14($this->close();), it don't have error but i don't remove it then it warning mysqli_query(): Couldn't fetch mysqli. It is at the end construct ???
My error: enter image description here
My code:
<?php
class Display extends Awebarts
{
private $conn;
private $tablename;
public function __construct($tablename)
{
$this->tablename = $tablename;
$this->connectToDb();
$this->conn = $this->getConn();
// insert the data into the table
$this->getData();
$this->close();
}
function getData()
{
$query = "SELECT * FROM $this->tablename ORDER BY `id` DESC LIMIT 1 ";
if(!$sql = mysqli_query($this->conn, $query)) {
throw new Exception("Error: Can not excute the query.");
} else {
$num = mysqli_num_rows($sql);
while($num > 0) {
//var_dump($data);
$data = mysqli_fetch_array($sql);
$num--;
}
}
return $data;
}
}
class Awebarts
{
private $cxn;
private $conn;
function connectToDb()
{
include "models/Database.php";
$vars = "include/vars.php";
$this->cxn = new Database($vars);
$this->conn = $this->cxn->getConn();
}
function getConn()
{
return $this->conn;
}
function close()
{
$this->cxn->close();
}
}
class Database
{
private $host;
private $user;
private $password;
private $database;
private $conn;
function __construct($filename)
{
if(is_file($filename)) {
include $filename;
} else {
throw new Exception("Error");
}
$this->host = $host;
$this->user = $user;
$this->password = $password;
$this->database = $database;
$this->connect();
$this->selectData();
}
function getConn()
{
return $this->conn;
}
private function connect()
{
// connect to the sercer
if(!mysqli_connect($this->host, $this->user, $this->password)) {
throw new Exception("Error: not connected to the server");
} else {
$this->conn = mysqli_connect($this->host, $this->user, $this->password);
}
return $this->conn;
}
private function selectData()
{
if(!mysqli_select_db($this->conn, $this->database)) {
throw new Exception("Error: No database");
}
}
function close()
{
mysqli_close($this->conn);
}
}
?>
The problem is that the connection is closed when you call getData() after you have created the Display object.
The getData() call in your constructor doesn't make any sense, because you don't use/save the return value. So when then constructor is executed you open a connection, send a select query (which return value you don't save) and then close the connection. After that a getData() call results in your error message.
You can either save the result of your getData() call from the constructor in a private field and access it later or remove the getData() and $this->close(); call from the constructor and call them from outside.
Try to perform method Database::connect like this:
private function connect()
{
// connect to the sercer
if(!$connect = mysqli_connect($this->host, $this->user, $this->password)) {
throw new Exception("Error: not connected to the server");
}
$this->conn = $connect;
return $this->conn;
}

PHP code convert to PHP/MySQLi OOP

today i tried to convert my code to PHP/MySQLi OOP code.
class Database
{
private $host;
private $user;
private $password;
private $db;
private $mysqli;
function __construct()
{
$this->host = "*****";
$this->user = "*****";
$this->password = "******";
$this->db = "*****";
$this->mysqli = new mysqli($this->host, $this->user, $this->password, $this->db);
if (mysqli_connect_errno()):
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
endif;
}
}
This is a script for the query's:
include_once("WD_Config/database.php");
class Adressen_Db
{
function __construct()
{
$this->database = new Database();
}
public function selecteer()
{
$query = "SELECT * FROM wd_adressen WHERE verborgen = 0 ORDER BY naam ASC";
$result = $this->database->mysqli->query($query);
return $result;
}
}
And this is how i call it.
$adressen = new Adressen_Db;
$adressen_result = $adressen->selecteer();
echo "<p>";
while ($row = $adressen_result->fetch_assoc()):
echo "<a href='http://maps.google.com/?q=".$row['voladres']."' target='_blank'>".$row['naam']."</a> woonachtig op <i>".$row['voladres']."</i><br>";
endwhile;
echo "</p>";
I alway get a "Call to a member function query() on a non-object". Doesn't matter what i trie ...
Can somebody tell me why that is?
Thanks!
The $mysqli variable in class Database is declared private.
You can access it only through setters and getters.
I think while you definitely need to have $mysqli as public so it can be accessed in the other method, there might be something else, as the error would be something like
trying to access private property in database class
or something like that, whereas your script throws a non-object call error
I think your new Adressen_Db; lacks the parenthesis:
$adressen = new Adressen_Db();
You can replace your code with this:
Config.php
<?php
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "your_database_name");
Now include this file in your database file
require_once 'config.php';
Class Database {
public $host = DB_HOST;
public $user = DB_USER;
public $pass = DB_PASS;
public $dbname = DB_NAME;
public $link;
public $error;
public function __construct() {
$this->getConnection();
}
private function getConnection() {
$this->link = new mysqli($this->host, $this->user, $this->pass, $this->dbname);
if (!$this->link) {
$this->error = "Connection failed" . $this->link->connect_error;
return false;
}
}
// for only select query
public function select($query) {
$result = $this->link->query($query) or
die($this->link->error . __LINE__);
if ($result->num_rows > 0) {
return $result;
} else {
return false;
}
}
// for insert, delete and update
public function myquery($query) {
$myquery = $this->link->query($query) or
die($this->link->error . __LINE__);
if ($myquery) {
return $myquery;
} else {
return false;
}
}
}
Now, make your queries like this:
<?php
require_once './lib/Database.php';
?>
<?php
class Admin {
private $db;
public function __construct() {
$this->db = new Database();
}
public function getData(){
$query = "SELECT * FROM admin";
$result = $this->db->select($query);
if($result != false){
while($row = $result->fetch_assoc()){
// do your thing
}
}
}
public function insert(){
$query = "INSERT INTO admin(admin_name) VALUES('$admin_name')";
$result = $this->db->myquery($query);
if($result){
$msg = "User has been added successfully.";
return $msg;
} else {
$msg = "Error while adding user. Please try again.";
return $msg;
}
}
}
Do this.

PHP Database Class Load Rows function (OOP)

I want to print out all content of the 'forum_question' table.
What am i doing wrong? No matter what, i will get the message "Nothing found!",
but i am sure the $db->connect DOES work, so it must be something with the query or loadRows functions.
This is my database class:
<?php
class Database {
private $host;
private $user;
private $password;
private $rows;
private $result;
private $dbName;
private $connection;
private $isReady;
public function __construct() {
$this->result = null;
$this->isReady = false;
}
/* setters */
public function setHost($host){ $this->host = $host; }
public function setUser($user){ $this->user = $user; }
public function setPassword($password){ $this->password = $password; }
public function setDbName($dbName){ $this->dbName = $dbName; }
/* Interface functions */
public function initiate($host=null,$user=null,$password=null,$dbName=null) {
if(isset($host,$user,$password,$dbName)==false) {
die("Please provide require settings.");
}
$this->setHost($host);
$this->setUser($user);
$this->setPassword($password);
$this->setDbName($dbName);
$this->isReady = true;
}
public function connect() {
if($this->isReady==false) {
die("Not ready to connect, please initiate connection");
}
$connection_string = "mysql:host=".$this->host.";dbname=".$this->dbName;
$this->connection = new PDO($connection_string, $this->user, $this->password);
$this->query("SET NAMES 'utf8'",$this->connection); // ensure character/language support
}
public function disconnect() {
$this->connection = null;
$this->isReady = false;
$this->setHost = null;
$this->setUser = null;
$this->setPassword = null;
$this->setDbName = null;
}
public function query($sql) {
$this->result = $this->connection->query($sql);
}
public function countRows() {
return $this->result->rowCount(); }
public function loadRows() {
if(!$this->result) die("Nothing found!");
$this->rows = array();
foreach ($this->result as $row) {
$this->rows[] = $row;
}
return $this->rows;
}
} // End of Database class
?>
This is my index file:
<?php
require_once 'class_database.php';
$db = new Database();
$db->initiate("localhost","USER","PASSWORD","DATABASE");
$db->connect();
$db->query("SELECT * FROM 'forum_question'");
$db->loadRows();
?>
Why don't you try with different connection script? For instance:
<?php
$mysql_server = "localhost";
$mysql_user = "USER";
$mysql_password = "PASSWORD";
$mysql_db = "DATABASE";
$mysqli = new mysqli($mysql_server, $mysql_user, $mysql_password, $mysql_db);
if ($mysqli->connect_errno) {
printf("Connection failed: %s \n", $mysqli->connect_error);
exit();
}
$mysqli->set_charset("utf8");
works fine, all you have to do is:
<?php
require_once "connection.php";
$query = "SELECT * FROM 'forum_question'";
$mysqli->query($query);
$mysqli->close();
Assuming that you saved the connection script in file "connection.php".

Categories