This question already has answers here:
Fatal error: Using $this when not in object context
(4 answers)
Closed 9 years ago.
i have this class for connect to mysql database using php/mysqli:
class AuthDB {
private $_db;
public function __construct() {
$this->_db = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME)
or die("Problem connect to db. Error: ". mysqli_error());
}
public function __destruct() {
$this->_db->close();
unset($this->_db);
}
}
now, i have any page for list user :
require_once 'classes/AuthDB.class.php';
session_start();
$this->_db = new AuthDB(); // error For This LINE
$query = "SELECT Id, user_salt, password, is_active, is_verified FROM Users where email = ?";
$stmt = $this->_db->prepare($query);
//bind parameters
$stmt->bind_param("s", $email);
//execute statements
if ($stmt->execute()) {
//bind result columnts
$stmt->bind_result($id, $salt, $pass, $active, $ver);
//fetch first row of results
$stmt->fetch();
echo $id;
}
now, i see this error:
Fatal error: Using $this when not in object context in LINE 6
How to fix this error?!
Like the error says, you can't use $this outside of the class definition. To use $_db outside the class definition, first make it public instead of private:
public $_db
Then, use this code:
$authDb = new AuthDb();
$authDb->_db->prepare($query); // rest of code is the same
--
You have to understand what $this actually means. When used inside a class definition, $this is used to refer to an object of that class. So if you had a function foo inside AuthDB, and you needed to access $_db from within foo, you would use $this to tell PHP that you want the $_db from the same object that foo belongs to.
You might want to read this StackOverflow question: PHP: self vs $this
Related
This question already has answers here:
Fatal error: Call to undefined method Database::prepare()
(3 answers)
Closed 3 years ago.
I want to create a new database using php oop class, I had Create 2 class the first class to connect to localhost only , and the second class to create a database in this localhost depending on connection class "first class"
class Connection
{
public $conn;
function __construct() {
try {
$this->conn = new PDO('mysql:host=127.0.0.1;charset=utf8', 'root', '');
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die($e->getMessage());
}
return $this->conn;
}
}
class CreateNewDataBase
{
public $connect;
function __construct()
{
$this->connect = new Connection;
$sql = 'CREATE DATABASE `startex` CHARACTER SET utf8 COLLATE utf8_general_ci';
$query = $this->connect->prepare($sql);
$query->execute();
if ($query) echo 'Done Your Database Is Created Successfuly';
}
}
$newObject= new CreateNewDataBase;
The output is
Fatal error: Uncaught Error: Call to undefined method
Connection::prepare()....CreateNewDataBase->__construct() thrown in my
file bath
Your Connection class does not have a prepare method.
The constructor isn't going to return what you have in the return statement when you are newing up a new instance of that class. It is for instantiating the object; you are not the caller of the __construct method at this moment.
$conn = new Connection;
This is assigning by reference the new object that is created by using the new keyword, regardless of any return statement in the constructor.
You could reach the PDO connection in the Connection class from inside CreateNewDataBase constructor though:
$this->connection->conn
This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 6 years ago.
I've been working on a databaseHandler php class, which should connect to the database and then be usable in other PHP files, atleast this was the plan. I've come across the problem that it cannot use any PDO related functions in my PHP class, i've tried checking if it was null, or not set at all (but it was) and i've also tried using a dummy function that just echos something which was to test if the class isn't undefined in others.
<?php
class databaseHandler {
private $db;
private static $instance;
function __construct() {
$this->buildDatabaseConnection();
}
public static function getInstance() {
if(!self::$instance) {
self::$instance = new databaseHandler();
}
return self::$instance;
}
private function buildDatabaseConnection() {
require 'dbconfig.php';
try {
$this->db = new PDO("mysql:host=" . HOST . ";dbname=" . DATABASE . ";charset=utf8", USER, PASSWORD);
if(isset($this->db)) {
if(!is_null($this->db)) {
echo "isn't null";
}
}
} catch(PDOException $e) {
$e->getMessage();
}
}
public function getConnection() {
return $this->$db;
}
public function getSomeShit() {
echo "some shit";
}
}
?>
The problem might be with the getConnection() php function, does it actually return the PDO object here? Because the main problem lays with the fact that i get this error when i use my getConnection function in other classes:
Notice: Undefined variable: database in F:\Websites\DevProject\php\functions.php on line 69
Fatal error: Uncaught Error: Call to a member function prepare() on null in F:\Websites\DevProject\php\functions.php:69 Stack trace: #0 F:\Websites\DevProject\php\functions.php(51): register('qwe', 'sdasd', 'asdasd', 'asdas', '01-01-1970') #1 F:\Websites\DevProject\register.php(123): datelessRegister('qwe', 'sdasd', 'asdasd', 'asdas') #2 {main} thrown in F:\Websites\DevProject\php\functions.php on line 69
and line 69 would be this:
$stmnt = $database->prepare("SELECT $username, $email FROM " . USERTABLE);
Where the $database variable is the class instance:
$database = databaseHandler::getInstance();
If i try to var_dump it in my registration php file, it'll tell me this:
object(databaseHandler)#1 (1) { ["db":"databaseHandler":private]=> object(PDO)#2 (0) { } }
However, when i use it inside of my function, it will say it is 'NULL', why is it null in a function but defined globally?
All the errors relate to the object, and in there it tells me the pdo is undefined (i've tried checking if it was null, but it wasn't!)
Any help would be great, thanks in advance.
In the return statement of getConnection method you should write the class variable without $:
return $this->db;
Also, you must do the queries on the PDO connection instead of your database handler class, so $database = databaseHandler::getInstance(); should be
$database = databaseHandler::getInstance()->getConnection();
or you can simply use the __call magic method to keep your code as it is right now:
public function __call($method, $args)
{
return call_user_func_array(array($this->db, $method), $args);
}
Also, to clarify how to use this class, you should call it inside every method you need the database to be used, not only once on the top of your file, because defining it there it will not be available inside your methods/functions unless you don't use the global statement to import the variable. However usage of the global variable is not encouraged and it is considered as a bad practice. An example on how to use the database would be:
public function doSomething()
{
$db = databaseHandler::getInstance()->getConnection();
$db->prepare(....);
}
public function doSomethingElse()
{
$db = databaseHandler::getInstance()->getConnection();
$db->prepare(....);
}
If you know there are many methods inside your class that uses the database then you can define it as a class variable and set the db instance in the constructor.
You seem to be having issues with scopes.
$database = databaseHandler::getInstance();
function doSomething()
{
// $database is not defined in this scope
$database->getConnection()->prepare(/* ... */);
}
You have to declare it as part of the global scope
function doSomething()
{
global $database;
$database->getConnection()->prepare(/* ... */);
}
The problem seems to be in the getConnection() function. Since $db is field you must do.
return $this->db;
However this is a very complex class structure for a simple problem.
You can directly extend your class from PDO
class DatabaseHandler extends PDO {
function __construct() {
parent::__construct('mysql:host=host_name;dbname=db_name', 'user_name', 'password');
parent::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
}
And create an object of this whenever you want to do database transaction.
$db = new DatabaseHandler();
$stmt = $db->prepare(".....");
$stmt->execute();
This question already has answers here:
When should I use 'self' over '$this'?
(23 answers)
Closed 6 years ago.
Only the part which is $this->link->query($query) I understand that link is the member variable of the class Database but don't understand what is happening when $this->link->query($query) executes? help, I am a novice at coding
My whole code:
<?php
class Database
{
public $db_host=DB_HOST;
public $db_user=DB_USER;
public $db_pass=DB_PASS;
public $db_name=DB_NAME;
public $link;
public $error;
public function __construct()
{
// Call connect function
$this->connect();
}
private function connect()
{
$this->link= new mysqli($this->db_host,$this->db_user,$this->db_pass,$this->db_name);
if(!$this->link)
{
$this->error="Connection Failed";
return false;
}
}
public function select($query)
{
$result=$this->link->query($query) or die ("Query could not execute");
}
}
?>
$this is the current Database object you are using.
-> calls a method or member of that object
link as you pointed out is a member of Database which just happens to be another object of mysqli.
query($query) is a method of link.
So you are calling mysqli query. Where the param $query should be your sql
$this->link is a database connection object, and it has a method called query() for doing database queries and returning a mysqli result object. The query() method takes an SQL string. So one way to invoke it would be:
$result = $this->link->query("SELECT * FROM table WHERE 1") ;
It's very common to use a variable instead of a string literal in calls to mysqli query():
$sql = "SELECT * FROM table WHERE 1" ;
$result = $this->link->query($sql) ;
In the case of your code, the variable containing the SQL string is called $query, which can be kind of confusing, especially since $query isn't defined anywhere that I can see.
This question already has answers here:
Call to a member function prepare() on a non-object PHP Help [duplicate]
(8 answers)
Closed 9 years ago.
Heres my code to connect to the database
function createConnection($DB_USER, $DB_PASSWORD){
$dbc = new PDO('mysql:host=****', $DB_USER, $DB_PASSWORD);
}
and below and is the code for a function being called
function checkIfUserExists($dbc, $username, $table){
global $dbc;
$stmt = $dbc->prepare("SELECT * FROM ? WHERE username = ?");
$stmt = bindParam(1, $table);
$stmt = bindParam(2, $username);
$stmt->execute();
}
below is the code i use to call them
$connect = new databaseOperations;
$connect->createConnection($DB_USER, $DB_PASSWORD);
$connect->checkIfUserExists($dbc, login, Username);
my question is why am i getting the call to a member function prepare() on a non-object error when the page loads?
You get that because the $dbc you pass to the checkIfUserExists method is not available in the global scope, only in the scope where it is created (in this case, the scope of createConnection).
The solution is simple: Never ever use globals in your code and the last code where you should use globals is in OOP code.
Use something like this:
class DatabaseOperations
{
private $dbc;
public function createConnection(...)
{
$this->dbc = new PDO(...);
}
public function checkIfUserExists(...)
{
$this->dbc->prepare(...);
// ...
}
}
$db = new DatabaseOperations();
$db->createConnection(...);
$db->checkIfUserExists(...);
Or return the $dbc variabele in the createConnection function and pass that to the other functions.
Important side note: This is surely not the way you should use classes. Read something about OOP and program like that. In that case, you usually have a method on the User (Active Record) or UserMapper (DataMapper) object to check if it exists.
function createConnection($DB_USER, $DB_PASSWORD){
$dbc = new PDO('mysql:host=****', $DB_USER, $DB_PASSWORD);
return $dbc; // <---- add this...
}
function checkIfUserExists($dbc, $username, $table){
// ---> no need to use global, because you pass $dbc as an argument
calling...
$dbc = $connect->createConnection($DB_USER, $DB_PASSWORD);
I'm just changing my website's MySQL to PDO, and I've got a strange problem when I tried to use PDO in an other class.
class Database {
private $pdo;
public function __construct() {
$this->pdo = new PDO('mysql:host=localhost;dbname=appdora;charset=utf8', 'root', 'root');
}
}
class doClass {
//Variables
private $db;
//PDO
public function __construct(Database $db) {
$this->db = $db;
}
And the code is returns with: the following error:
Catchable fatal error: Argument 1 passed to doClass::__construct() must be an instance of Database, none given, called in .../index.php on line xx and defined in ../classes.php on line xx
The code:
$do = new doClass();
if ($do->loginCheck()) { echo 'loginOk'; } else { 'loginError'; }
loginCheck() is a simle function that works without classes!
Could you help me, what's the problem?
Thanks in advance!
$do = new doClass();
You defined your doClass class to expect a parameter in the constructor:
public function __construct(Database $db)
So you need to supply that parameter of type Database to successfully construct the object.
For example, if you have a database object stored before somewhere inside a variable $database, you can simply pass it to the constructor of doClass like this:
$do = new doClass($database);