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);
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);
I know this is an old question but I am not finding answer. Here is my code:
class SqlConnect implements connectionInterface {
//put your code here
private $datasource=null;
private $credentials = null;
public function __construct() {
$netsConn = new configInit(); // Here where the error is happing
$datasource = $this->$netsConn->getDatabase();
$credentials = $this->$netsConn->getBasicCredentials();
}
public function connect()
{
$conn = mysqli_connect($datasource['servername'], $credentials['username'], $credentials['password']);
if (!$conn)
{
die("Connection failed: " . $conn->connect_error);
} else {
return $conn;
}
}
}
I am then calling the class like
class applicationsController implements Controller {
private $conn = null;
public function __construct() {
$conn = new SqlConnect();
$this->$conn->connect();
}
...
}
However I am getting the following error:
Catchable fatal error: Object of class configInit could not be converted to string
This error happens in SqlConnect. I have looked through about 6 answers on stackoverflow and most all of them were about trying to echo some objects, which is not my case
Ahh, I think I see it.
You are assigning to global variable $netsConn, not object property $netsConn ...
Try this:
private $netsConn;
...
$this->netsConn = new configInit();
... that is, if you want to keep it around. Otherwise, refer directly to the variable not to a (never-declared ...) property.
The reason you get the error is because of the following 2 lines
netsConn = new configInit(); // Here where the error is happing
$datasource = $this->$netsConn->getDatabase();
First line is fine, but on the second line, you are using $netsConn as an attribute name for the SqlConnect class ($this). For this to work, php has to use the string representation of $netsConn by attempting to call it's implementation of the magic method __toString(). Since this probably does not exist in your configInit() class, you end up with that error.
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);
So, in short I'd like my login class to not have to create a new instance of my DB class within in function. Currently I'm trying to do it like this:
<?php
class siteLogin
{
private $db;
private $dataStore;
function __construct()
{
if (!isset($_SESSION)) {
session_start();
}
require_once '../application/db.php';
$this->$db = new DB();
require_once '../application/data.php';
$this->$dataStore = new Data($db);
}
But I get the error:
Fatal error: Cannot access empty property in C:\var\www\sexdiaries.co.uk\class\siteLoginClass.php on line 16
I would like to give give $this->$db the reference to siteLogin class.
You're not using the right notation for properties. Try this instead:
$this->db = new DB();
$this->dataStore = new Data($db);
They aren't prefixed with $ like normal variables. This is because you can use variable property names in PHP, e.g.
$foo = 'db';
echo $this->$foo; // equivalent to `echo $this->db;`
In your case, $db was an undefined variable that got initialised to an empty string (although a PHP notice would have been triggered - do you have error reporting on?), so you were effectively trying to access a property of the same name, hence the error Cannot access empty property.
This question already has answers here:
Call to a member function on a non-object [duplicate]
(8 answers)
Closed 9 years ago.
I have this code:
<?php
class guildData {
public $email = NULL;
public $hash_pw = NULL;
public $user_id = NULL;
public $clean_username = NULL;
public $display_username = NULL;
public function selectGuild($g_id)
{
global $db,$db_table_prefix;
$this->g_id = $g_id;
$sql = "SELECT
name
FROM
guild
WHERE
id = '".$g_id."'";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
return ($row['name']);
}
}
?>
<?php echo $guildData->selectGuild(1); ?>
I'm simply getting a 500 error and IDEone gave me this also:
Fatal error: Call to a member function selectGuild() on a non-object in /home/VT00Ds/prog.php on line 32
I can not see the error, can you help me?
You are doing it wrong.
Get rid of the global variables. Instead , if the class needs DB access , then you should inject it in the constructor:
class GuildData
{
// ... snip
protected $connection;
public function __construct( PDO $connection )
{
$this->connection = $connection;
}
// ... snip
}
Your code has potential for SQL injections. Instead of concatenating the query, you should use prepared statements:
$statement = $this->connection->prepare(
'SELECT name FROM guild WHERE id = :id'
);
$statement->bindParam( ':id', $this->g_id, PDO::PARAM_INT );
if ( $statement->execute() )
{
$data = $statement->fetch( PDO::FETCH_ASSOC );
}
You have to instantiate object, before you can use them:
$pdo = new PDO('mysql:host=localhost;dbname=myMagicalDB;charset=UTF-8',
'username', 'password');
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$guild = new GuildData( $pdo );
$guild->selectGuild(42);
You might consider separating the part with deals with DB from the domain logic. Essentially letting some other class to handle the fetching and storing the data, while the Guild class manages the logic. You might find this and this answer relevant.
Do not use public variables. You are breaking the encapsulation of the object by directly exposing the internal data. Instead you should define them as protected or private.
You might also take a hard look at what you are actually keeping there. Why does GuildData need $hash_pw or $clean_username ?
You haven't instantiated $guildData. If you want to use this method without instantiating an object, the method should be static.
class guildData {
public static function selectGuild($g_id) { ... }
}
Then you can call it from
echo guildData::selectGuild(1);
Otherwise, you need to instantiate an object
$guildData = new GuildData();
echo $guildData->selectGuild(1);
Also, you should have some sort of __construct() method in there, in order to set up your member variables.
UPDATE I also noticed an error in your selectGuild() method:
$this->g_id = $g_id;
Sets the value of g_id, which is not defined as a member variable in the class. You must declare g_id as a member variable in your class definition:
class guildData {
public $email = NULL;
public $hash_pw = NULL;
public $user_id = NULL;
public $clean_username = NULL;
public $display_username = NULL;
public $g_id = NULL;
.
.
.
}
Finally, sql_query() is not a PHP method that I've ever heard of. Unless you're using a library that defines these methods, I think you mean mysql_query(). If this is the case, you should stop using mysql_* functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use, read this SO article.