I'm having trouble using a class's static method, with mysqli_real_escape_string - I'm getting an error:
Fatal error: Using $this when not in object context in C:\Users\Duncan\Websites\...\logic\clsDb.php on line 42
I'm trying to build an Interface, Class implementing it and get it working (all in one php file, called clsDB.php).
The issue I'm having is with returning the myslqi_real_escape_string value.
Line 42 (red highlight): Class code in method generating the error message.
Line 87 (blue highlight): Class method call for db usage example.
Please let me know if you see any other issues with this code:
Code: Select all
<?php
// clsDb.php
interface Db{
public function connect();
public function error();
public function errno();
public static function escape_string($string);
public function query($query);
public function fetch_array($result);
public function fetch_row($result);
public function fetch_assoc($result);
public function fetch_object($result);
public function num_rows($result);
public function close();
}
class mySqlDb implements Db{
private $link;
public function connect($server='', $username='', $password='', $new_link=false, $client_flags=0){
$this->link = new mysqli($server, $username, $password, $new_link, $client_flags);
}
//Logs in using the standard connection for exampleuserdb - root user.
public function connectStandard(){
$this->link = new mysqli('localhost', 'root', '', 'exampleuserdb', 0);
}
public function errno(){
return $this->link->errno();
}
public function error(){
return $this->link->error();
}
public static function escape_string($string){
[color=#FF0000]return $string = $this->link->real_escape_string($string);[/color]
//$string = $this->link->real_escape_string($string);
//return $string;
//return mysqli_real_escape_string($link, $string);
//return mysqli_real_escape_string($link, $string);
}
public function query($query){
return $this->link->query($query);
}
public function fetch_array($result, $array_type = MYSQL_BOTH){
return $result->fetch_array($array_type);
}
public function fetch_row($result){
return $result->fetch_row();
}
public function fetch_assoc($result){
return $result->fetch_assoc();
}
public function fetch_object($result){
return $result->fetch_object();
}
public function num_rows($result){
return $result->num_rows;
}
public function close(){
return $this->link->close();
}
}
//Usage example
$db = new mySqlDb;
//If you want to specify a different, username, pass or database use 'connect'
//$db->connect('localhost', 'root', '');
$db->connectStandard();
$fred = 'Freds';
[color=#0000FF]$fred = $db->escape_string($fred);[/color]
echo $fred;
$db->query('use exampleuserdb');
$result = $db->query("SELECT username from users");
while($row = $db->fetch_assoc($result)){
echo($row['username']);
}
$db->close();
?>