Okay so I'm basically trying to improve with PHP OOP, however I'm not too sure how I should do this. Could someone please point out the issue?
The code returns the following errors:
Notice: Undefined property: registration::$userExist
Fatal error: Call to a member function fetch() on a non-object
The class:
class registration extends connect{
public function userExist(){
global $dsn;
$userExist = $this->dsn->prepare("
SELECT * FROM accounts
WHERE username= :username
");
$userExist->bindParam(':username', $username);
$userExist->execute();
$rows = $this->userExist->fetch(PDO::FETCH_NUM);
return $rows;
}
How I'm trying to use the class on a page:
$conn = new connect();
$registration = new registration();
$rows = $registration->userExist();
if($rows < 1){
// do something
The error says that it cannit find variable $userExist, this is because on the last line you are looking for variable "$userExist" inside "$this" while you defined it as a normal variables a few lines above it.
To fix the problem, drop the this-> part of the line that gives the error so it pick up the variable from the local scope
$rows = $userExist->fetch(PDO::FETCH_NUM);
EDIT
You said in comments that variable $username was properly defined before you called the method userExists(). However, in php variables won't be copied over to inside of the function code block when they are called. To pass variables you need to add an argument to the function.
public function userExist($username){
...
$rows = $userExist->fetch(PDO::FETCH_NUM);
....
}
And you need to use it like:
....
$rows = $registration->userExist($username);
....
You don't need $this->userExist
class registration extends connect{
public function userExist(){
global $dsn;
$this->dsn = $dsn; // assign global $dsn to $this->dsn
$userExist = $this->dsn->prepare("SELECT * FROM `accounts` WHERE `username`= :username");
$userExist->bindParam(':username', $username);
$userExist->execute();
$rows = $userExist->fetch(PDO::FETCH_NUM);
return $rows;
}
This happens because you don't have a property userExist in the class registration.
Just change
$rows = $this->userExist->fetch(PDO::FETCH_NUM);
for
$rows = $userExist->fetch(PDO::FETCH_NUM);
Related
I've seen other posts about this but I just can't understand them, what is the solution here, can you guys show me? Please. Static or not static? What does it mean? Is this the problem?
Db connection code:-
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'not telling');
class DB_con {
public $connection;
function __construct(){
$this->connection = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD,DB_DATABASE);
if ($this->connection->connect_error)
die('Database error -> ' . $this->connection->connect_error);
}
function ret_obj(){
return $this->connection;
}
}
Code for fetching records:-
<?php
$role_id = (isset($_SESSION['role_id']) ? $_SESSION['role_id'] : 4) ;
$query = "
SELECT rights_codename FROM permissions
INNER JOIN roles_and_permissions ON fk_permissions_id = permissions_id
WHERE fk_role_id = $role_id
";
$_SESSION['permissions'] = array();
$result = $this->db->query($query);
while($row = $result->fetch_assoc()){
array_push($_SESSION['permissions'], $row['permissions_cname']);
// $_SESSION['permissions'][] = $row['permissions_cname'];
}
if(in_array('admin_rediger_bruger',$_SESSION['permissions'])){
}
?>
Fatal error: Uncaught Error: Using $this when not in object context in C:\xampp\htdocs\R_L_E\login.php:30 Stack trace: #0 {main} thrown in C:\xampp\htdocs\R_L_E\login.php on line 30
In lay man terms, $this is when you are referencing a non static function in a class. What you can do is create a new instance of the database class and then use that variable created during instantiation to access the member functions of that class
Do this
$conn = new DB_con();//instantiate the class.add this at the very top of login.php
$conn->connection->query('your sql stuff');//replace the $this->db->query($query) with this line
You can access the connection property as it is declared as public in your class
Also do not forget to include the DB_con file
$this is a variable that refers to "the current object" when you're running code inside that object. That means, when you write this:
class AClass {
public function foo() {
var_dump($this);
}
}
$my_object = new AClass;
$my_object->foo();
Then $this is the same as $my_object during the execution of the foo() function. You can think of it like an extra parameter to the function, once you leave that function it won't exist any more.
So when you write this:
$result = $this->db->query($query);
You need to be inside some method which has been called on a particular object, so that there is an object for $this to refer to. If you're in global code, or a function that's not part of a class, or a static method, there is no "current object", so $this doesn't exist.
In your case, you're trying to get to some instance of a DB connection object. That means somewhere in your code you need to have created that object, and assigned it to a variable, then you can reference that variable. You can call that variable whatever you like, but you can't call it $this, because that's a reserved name.
Your DB_Con class doesn't have a query() method, so it looks like you want to get the MySQLi object out first, and then call the method on that.
So you would write something like:
$my_db_connection = new DB_Con;
$mysqli_connection = $my_db_connection->connection;
// or: $mysqli_connection = $my_db_connection->ret_obj();
$result = $mysqli_connection->query($query);
Or more concisely:
$my_db_connection = new DB_Con;
$result = $my_db_connection->connection->query($query);
// or: $result = $my_db_connection->ret_obj()->query($query);
So when I run this below it outputs an error Catchable fatal error: Object of class eg could not be converted to string
spl_autoload_register(function($class) {
require_once '../dbfolder/'.$class.'.php';
});
$mysql = dbWrapper::getDbInstance();
class eg
{
private $username = 'paul';
private $email = 'paul#yahoo.com';
public function eg_()
{
global $mysql;
$sql = "INSERT INTO users(username,email)VALUES(:username,:email)";
$prepared = $mysql->$this->handler->prepare($sql);
$prepared->bindParam(':username',$this->username);
$prepared->bindParam(':email',$this->email);
$prepared->execute();
}
}
$eg = new eg();
$eg->eg_();
Please can anyone just point out for me what am doing wrong?
This line is the problem:
$prepared = $mysql->$this->handler->prepare($sql);
PHP thinks you're trying to use it's variable variable feature. It sees $mysql->$this and tries to convert $this into a string, which the current class does not support (no __toString() magic method). I assume this is a typo/copy-paste error.
To fix it, all you need is to remove it (assuming your $mysql object has a property of handler that is):
$prepared = $mysql->handler->prepare($sql);
I've a simple class, User which requires database access. I also require database access in several other classes, so my class.user.php looks like this:
include "config.php"
class User {
public $db;
public function __construct(PDO $db){
$this->db = $db;
global $db;
}
function LastLogin(){
// global $db; // if I uncomment this, it works for this function.
$pdo = $db->prepare("SELECT last_login FROM users WHERE username = ?");
$pdo->execute(array($username));
while($r = $pdo->fetchObject()){
echo $r->last_login;
}
}
}
Config.php looks like this:
$dsn = "mysql:host=localhost;dbname=db;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$db = new PDO($dsn,'user','pass', $opt);
So let's say I have page called userdetails.php, and I want to know when the user has last logged in.
$user = new User($db);
$user->LastLogin();
This results in a error message like this:
Notice: Undefined variable: db in /home/www/class.user.php on line 12
Fatal error: Call to a member function prepare() on a non-object in/home/www/class.user.php on line 12
So I'm having problems with using pdo inside the class. It makes no sense to type "global $db" to every function, so what am I doing wrong?
As stated in the comments, remove the line:
global $db;
Also, you don't need to pass the PDO either.
And instead of trying to reference it as
$db->prepare(....)
You want to reference it as:
$this->db->prepare(....)
since you're instantiating it as a variable accessible within the class.
try this
include "config.php"
class User {
public $db;
public function __construct($db){
$this->db = $db;
}
function LastLogin(){
$pdo = $this->db->prepare("SELECT last_login FROM users WHERE username = ?");
$pdo->execute(array($username));
while($r = $pdo->fetchObject()){
echo $r->last_login;
}
}
}
The global $db is definitely not required and is bad practice as it destroys the encapsulation of a class.
The type hint PDO in __construct(PDO $db) is also not actually legal as far as I know.
And while you have a property of $db and loaded it with the correct handle, to use it chnage this
$pdo = $db->prepare("SELECT last_login FROM users WHERE username = ?");
To
$pdo = $this->db->prepare("SELECT last_login FROM users WHERE username = ?");
So you are using/addressing it correctly.
global $db is the problem. Loose it and it all should work.
Remove global $db from your constructor.
Use $this->db instead of $db in function LastLogin
I have a database class with several PDO functions inside (db.inc.php). I'm trying to call this function from another function:
// Query method
public function query($query) {
$this->stmt = $this->dbh->prepare($query);
}
In my global PHP file I have instantiated the database using:
// Instantiate database
$database = new database();
However when trying to call this function from another function inside of a different PHP file (user.inc.php):
function confirmAccount($key,$id) {
// Check key and id against entry in database
$database->query('SELECT * FROM users WHERE id = :id');
}
I get the following error:
Fatal error: Call to a member function query() on a non-object in /home/studevne/public_html/includes/user.inc.php on line 10
All of my PHP files are included in the global PHP file as so:
include_once 'includes/db.inc.php';
include_once 'includes/echo.inc.php';
include_once 'includes/tools.inc.php';
include_once 'includes/user.inc.php';
I'm guessing its something to do with the scope of the database class and its functions howevver I'm a little confused on how to solve this. Any help is greatly appreciated.
You need to pass $database into the function, else it's out of scope. You can either pass it in as a parameter:
function confirmAccount($key,$id,$database) {
// Check key and id against entry in database
$database->query('SELECT * FROM users WHERE id = :id');
}
Or as a global:
function confirmAccount($key,$id) {
global $database;
// Check key and id against entry in database
$database->query('SELECT * FROM users WHERE id = :id');
}
globals are generally frowned upon, as they make it very easy to write messy code.
I'm working for admin login please anybody fix that..
Email: <?php echo $admin->get_email(); ?>
Fatal error: Call to a member function get_row() on a non-object in D:\MyWebSite\business_design\admin\admin-class.php on line 82
The code:
public function get_email() {
$username = $_SESSION['admin_login'];
global $db;
$info = $db->get_row("SELECT `email` FROM `user` WHERE `username` = '" . $db->escape($username) . "'");
if(is_object($info))
return $info->email;
else
return '';
}
Okay, are you using a framework?
Your $db variable is not instantiated, so when you call $db->get_row:
PHP can't find the $db object; and so,
get_row() can't exist.
To start with, make sure you know which class $db should be referring to. The same class will have the function "get_row"
First you have to include that class file in your php scrip file. That can be done easily by following script -
function __autoload($class_name){
require_once("RELATIVE_ADDRESS_OF_THE_CLASS".$class_name.".php");
}
Say for example you have your class is Database, so you should first instantiate $db as below -
$db = new Database();
Later if all the scripts are working properly in "Database" class, it should work straightaway...
Hope it helps..