Zdravim, som zaciatocnik v php oop. Chcel som si urobit vlastnu triedu pre ulahsenie prace s databazou. Nejde o nic super, len pre vlastne potreby. Hadze to chybu: Fatal error: Using $this when not in object context in C:\xampp\htdocs\db.class.php on line 50..Na 50 riadku mam
Kód:
if($this->type == 'mysqli'){
Bol by som rad, kebyze mi ukazete, kde robim chybu.
Kód:
<?php
Class DB{
/**
* @var object
* Database connection
*/
private static $connection = null;
/**
* @var String
* Type of Database
* Default MySQLi
*/
private $type = 'mysqli';
/**
* @var String
* SQL Query
*/
private $query = '';
private static $hostname = 'localhost';
private static $username = 'root';
private static $password = '';
private static $dbname = 'fontilate';
private static $port = 3306;
public function __contruct(){
}
public static function getConnection(){
if($this->type == 'mysqli'){
$this->connection = new mysqli($this->hostname,$this->username,$this->password,$this->dbname,$this->port);
}
if(!$this->connection){
echo $this->connection->connect_errno();
}else{
$this->connection->query('SET NAMES utf8');
return $this->connection;
}
}
/**
* Quering SQL
* @return result
*/
public function sqlQuery($query){
return $this->connection->query($query);
}
/**
* Fetch Assoc
* @var array
*/
public function fetchAssoc($result,$type_assoc){
switch($type_assoc){
case 'ASSOC': $fetch = 'MYSQLI_ASSOC';
case 'NUM': $fetch = 'MYSQLI_NUM';
}
$res = array();
while($tmp = $result->fetch_array($fetch)){
$res[] = $tmp;
}
return $res;
}
/**
* SQL Select
*/
public function select($select){
$this->query = 'SELECT ' . $this->escape($select);
return $this->query;
}
/**
* SQL From
*/
public function from($from){
$this->query .= 'FROM ' . $this->escape($from);
return $this->query;
}
/**
* SQL Where
*/
public function where($where){
$this->query .= 'WHERE ' . $this->escape($where);
return $this->query;
}
/**
* SQL Limit
*/
public function limit($limit){
$this->query .= 'LIMIT ' . $this->escape($limit);
return $this->query;
}
/**
* Escape String - Prevent for SQL Injection
*/
public function escape($string){
if($this->type == 'mysqli'){
return $this->connection->real_escape_string($string);
}else{
return addslashes($string);
}
}
}
$db = new DB();
$db->getConnection();
$result = $db->select('*')->from('users')->where('id = 10');
$fetch = $result->fetchAssoc('ASSOC');
foreach($fetch as $data){
echo $data['name'];
}
?>