'cannot access empty property' error in php - php

I am confused where i made mistake in my php code below. Although, i looked numerous time on my code but couldn't find why i am getting this error 'cannot access empty property' .
class DBTest{
//declare variables
private $servername = "localhost";
private $username = "root";
private $password = "";
private $database = "avn_test";
private static $conn;
private $results;
//constructor
public function __construct(){
self::$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();}
} //close constructor
public function executeQuery($query='') {
if(!empty($query)){
$query = self::$conn->real_escape_string($query);
Error on this line:
$this->results = self::$conn->query($query) or die("Error in database
connection".self::$conn->$error);
if( $this->results->num_rows > 0 ) {
$rowqry = array();
while($row = $this->results->fetch_object()) {
$rowqry[]= $row; } //close of while
$rarray['returnvar'] = $rowqry;
return $rarray;
} else {
return false; } // close of else
}//close of top if
else
return false;
} //close of function
function __destruct(){
self::$conn->close();}
} //close of class
//create an object of class DBTest
$test = new DBTest();
$q= "select * from test";
$tmp = $test->executeQuery($q);
if($tmp){
foreach($tmp as $key => $value){
echo $value;}
}
else
echo 'tmp var is empty';

In this line:
$this->results = self::$conn->query($query) or die("Error in database connection".self::$conn->$error);
Replace self::$conn->$error with self::$conn->error.
The $ is required when accessing a static property, but not needed for instance properties.

No need of $ in $conn function
self::$conn replace with self::conn
^^^^^^

Related

Can't connect to the database with my class?

I'm trying to connect to my database but it won't connect. I tried but won't connect. the error I'm getting is Parse error: syntax error, unexpected 'connect' (T_STRING) in C:\htdocs\www\dating\index.php on line 3. I called the tried new Database connect(); and tried connect(); I get this message Fatal error: Call to undefined function connect() in C:\htdocs\www\dating\index.php on line 3. What's wrong?
class Database{
private $db_host = "localhost";
private $db_user = "123346";
private $db_pass = "12345";
private $db_name = "1234";
public $conn;
// Create connection
public function connect(){
if(!isset($this->conn)){
$this->conn = new mysqli_connect($this->db_host,$this->db_user,$this->pass,$this->db_name);
if($this->conn){
$this->conn = true;
return true;
}else{
$this->conn = false;
return false;
}
}
}
public function disconnect(){
if(isset($this->conn)){
if(mysqli_close($this->conn)){
$this->myconn = false;
echo "connection closed";
return true;
} else{
echo "failed to close connection";
return false;
}
}else{
echo "no connection prescent";
}
}
}
I'm trying to get use query now but it won't get the results. Here is the code
include("functions/connect.php");
$db = new Database("localhost", "12345", "1234", "123");
$db->connectdb();
$db->select('rpg');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT id, username FROM users ORDER by ID DESC ";
if ($result = $db->query($query)) {
/* fetch object array */
while ($row = $result->fetch_row()) {
printf ("%s (%s)\n", $row[0], $row[1]);
}
/* free result set */
$result->close();
}
/* close connection */
$db->close();`
Please change this line
$this->conn = new mysqli_connect($this->db_host,$this->db_user,$this->pass,$this->db_name);
to this
$this->conn = new mysqli_connect($this->db_host,$this->db_user,$this->db_pass,$this->db_name);
You will notice you used $this->pass but it should be $this->db_pass.
To call the function of Database class you have to write your code like this;
<?php
include("functions/connect.php");
$db_conn = new Database();
if($db_conn->connect()) {
echo "Database connected";
}

Simple mySQLi select to an array

Building from a tutorial I found online.
I m trying to select all items from the 'items' table and create an array. Not sure how this is suppose to work. This $result = $this->connection->query($q); is what is causing the problem.
<?php
//DB.class.php
class DB {
protected $db_name = 'dbname';
protected $db_user = 'user';
protected $db_pass = 'pass';
protected $db_host = 'localhost';
protected $connection;
public function connect() {
$connection = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
// check connection
if ($connection->connect_error) {
trigger_error('Database connection failed: ' . $connection->connect_error, E_USER_ERROR);
}
}
public function resultToArray($result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
public function sel($table) {
$q = "SELECT * FROM $table";
$result = $this->connection->query($q);
$rows = $this->resultToArray($result);
return $rows;
$result->free();
}
}
make a construct function like
public $mysqli;
public function __construct()
{
$mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
$this->mysqli = $mysqli;
}
public function sel($table,$whr)
{
$query = "SELECT * FROM ".$table." where id='$whr'";
$result = $this->mysqli->query($query);
$total = array();
while($row = $result->fetch_assoc()){
//print_r($row);die;
$total[] = $row;
}//print_r($total);die;
return $total;
}
I think you should set a constructor, but if you don't want, just return an instance of it first and set your $this->connection property instead of $connection (the normal variable):
class DB {
protected $db_name = 'test';
protected $db_user = 'test';
protected $db_pass = 'test';
protected $db_host = 'localhost';
protected $connection;
public function connect() {
$this->connection = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
// ^^ this one, not $connection
// check connection
if ($this->connection->connect_error) {
trigger_error('Database connection failed: ' . $connection->connect_error, E_USER_ERROR);
}
return $this->connection; // then return this
}
public function resultToArray($result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
public function sel($table) {
$q = "SELECT * FROM $table";
$result = $this->connection->query($q);
// ^ so that if you call this, you have the mysqli object
$rows = $this->resultToArray($result);
return $rows;
$result->free();
}
}
$db = new DB(); // instantite,
$db->connect(); // then connect, shouldn't have to have this if you put the connection automatically on construct
$result = $db->sel('users'); // feed a valid existing table name
echo '<pre>';
print_r($result);

OOP database connect/disconnect class

I have just started learning the concept of Object oriented programming and have put together a class for connecting to a database, selecting database and closing the database connection. So far everything seems to work out okay except closing the connection to the database.
class Database {
private $host, $username, $password;
public function __construct($ihost, $iusername, $ipassword){
$this->host = $ihost;
$this->username = $iusername;
$this->password = $ipassword;
}
public function connectdb(){
mysql_connect($this->host, $this->username, $this->password)
OR die("There was a problem connecting to the database.");
echo 'successfully connected to database<br />';
}
public function select($database){
mysql_select_db($database)
OR die("There was a problem selecting the database.");
echo 'successfully selected database<br />';
}
public function disconnectdb(){
mysql_close($this->connectdb())
OR die("There was a problem disconnecting from the database.");
}
}
$database = new database('localhost', 'root', 'usbw');
$database->connectdb();
$database->select('msm');
$database->disconnectdb();
When I attempt to disconnect from the database I get the following error message:
Warning: mysql_close(): supplied argument is not a valid MySQL-Link resource in F:\Programs\webserver\root\oop\oop.php on line 53
I'm guessing it isn't as simple as placing the connectdb method within the parenthesis of the mysql_close function but can't find the right way to do it.
Thanks
I would add a connection/link variable to your class, and use a destructor.
That will also save you from haveing to remember to close your connection, cause it's done automatically.
It is the $this->link that you need to pass to your mysql_close().
class Database {
private $link;
private $host, $username, $password, $database;
public function __construct($host, $username, $password, $database){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->link = mysql_connect($this->host, $this->username, $this->password)
OR die("There was a problem connecting to the database.");
mysql_select_db($this->database, $this->link)
OR die("There was a problem selecting the database.");
return true;
}
public function query($query) {
$result = mysql_query($query);
if (!$result) die('Invalid query: ' . mysql_error());
return $result;
}
public function __destruct() {
mysql_close($this->link)
OR die("There was a problem disconnecting from the database.");
}
}
Example Usage:
<?php
$db = new Database("localhost", "username", "password", "testDatabase");
$result = $db->query("SELECT * FROM students");
while ($row = mysql_fetch_assoc($result)) {
echo "First Name: " . $row['firstname'] ."<br />";
echo "Last Name: " . $row['lastname'] ."<br />";
echo "Address: " . $row['address'] ."<br />";
echo "Age: " . $row['age'] ."<br />";
echo "<hr />";
}
?>
Edit:
So people can actually use the class, I added the missing properties/methods.
The next step would be to expand on the query method, to include protection against injection, and any other helper functions.
I made the following changes:
Added the missing private properties
Added __construct($host, $username, $password, $database)
Merged connectdb() and select() into __construct() saving an extra two lines of code.
Added query($query)
Example Usage
Please if I made a typo or mistake, leave a constructive comment, so I can fix it for others.
edit 23/06/2018
As pointed out mysql is quite outdated and as this question still receives regular visits I thought I'd post an updated solution.
class Database {
private $mysqli;
private $host, $username, $password, $database;
/**
* Creates the mysql connection.
* Kills the script on connection or database errors.
*
* #param string $host
* #param string $username
* #param string $password
* #param string $database
* #return boolean
*/
public function __construct($host, $username, $password, $database){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->mysqli = new mysqli($this->host, $this->username, $this->password)
OR die("There was a problem connecting to the database.");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$this->mysqli->select_db($this->database);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
return true;
}
/**
* Prints the currently selected database.
*/
public function print_database_name()
{
/* return name of current default database */
if ($result = $this->mysqli->query("SELECT DATABASE()")) {
$row = $result->fetch_row();
printf("Selected database is %s.\n", $row[0]);
$result->close();
}
}
/**
* On error returns an array with the error code.
* On success returns an array with multiple mysql data.
*
* #param string $query
* #return array
*/
public function query($query) {
/* array returned, includes a success boolean */
$return = array();
if(!$result = $this->mysqli->query($query))
{
$return['success'] = false;
$return['error'] = $this->mysqli->error;
return $return;
}
$return['success'] = true;
$return['affected_rows'] = $this->mysqli->affected_rows;
$return['insert_id'] = $this->mysqli->insert_id;
if(0 == $this->mysqli->insert_id)
{
$return['count'] = $result->num_rows;
$return['rows'] = array();
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
$return['rows'][] = $row;
}
/* free result set */
$result->close();
}
return $return;
}
/**
* Automatically closes the mysql connection
* at the end of the program.
*/
public function __destruct() {
$this->mysqli->close()
OR die("There was a problem disconnecting from the database.");
}
}
Example usage:
<?php
$db = new Database("localhost", "username", "password", "testDatabase");
$result = $db->query("SELECT * FROM students");
if(true == $result['success'])
{
echo "Number of rows: " . $result['count'] ."<br />";
foreach($result['rows'] as $row)
{
echo "First Name: " . $row['firstname'] ."<br />";
echo "Last Name: " . $row['lastname'] ."<br />";
echo "Address: " . $row['address'] ."<br />";
echo "Age: " . $row['age'] ."<br />";
echo "<hr />";
}
}
if(false == $result['success'])
{
echo "An error has occurred: " . $result['error'] ."<br />";
}
?>
you're not returning anything from connectdb() yet you're passing this function's return to mysql_close().
You should be aware that mysql_* functions were introduced in PHP 4, which is more then 1 yours ago. This API is extremely old, and the process has begun to actually deprecating this extension.
You should not in 2012 write new code with mysql_* functions.
There exist two very good alternative : PDO and MySQLi. Both of which are already written with object oriented code in mind, and they also give you ability to use prepared statements.
That example you showed in the original post written with PDO would look like this:
//connect to the the database
$connection = new PDO('mysql:host=localhost;dbname=msm', 'username', 'password');
//disconnects
$connection = null;
Of course there are more complicated use-case, but the point stand - time to evolve.
mysql_close requires a parameter to disconnect but you are providing nothing.
class Database {
private $host, $username, $password, $con;
public function __construct($ihost, $iusername, $ipassword){
$this->host = $ihost;
$this->username = $iusername;
$this->password = $ipassword;
$this->con = false;
}
public function connect() {
$connect = mysql_connect($this->host, $this->username, $this->password);
return $connect;
}
public function connectdb(){
$conn = $this->connect();
if($conn)
{
$this->con = true;
echo "Successsfully Connected. ";
return true;
}
else {
echo "Sorry Could Not Connect. ";
return false;
}
}
public function select($database){
if($this->con)
{
if(mysql_select_db($database))
{
echo "Successfully Connected Database. $database. ";
return true;
}
else
{
echo "Unknown database. ";
}
}
else {
echo "No active Connection. ";
return false;
}
}
public function disconnectdb(){
if($this->con)
{
if(mysql_close($this->connect()))
{
$this->con = false;
echo "Successfully disconnected. ";
return true;
}
}
else
{
echo "Could Not disconnect. ";
return false;
}
}
}
$database = new database('localhost', 'root', '');
$database->connectdb();
$database->select('databaseoffacebook');
$database->disconnectdb();
Object Oriented Programming works well with PDO and mysqli. Give it a try
<?php
class Database{
private $link;
//private $host,$username,$password,$database;
//private $status;
public function __construct(){
$this->host = 'localhost';
$this->username = 'root';
$this->password = '';
$this->database = 'workclass';
$this->link = mysqli_connect($this->host,$this->username,$this->password);
$this->status = mysqli_select_db($this->link,$this->database);
if (!$this->status) {
return $this->status="Failed to Connected with Database";
}else{
return $this->status="Database is connected";
}
}
}
$object = new Database();
echo $object->status;
?>

PHP mySQL connection problems

Ok, I am completely baffled.
I am setting up an OO site. I have a class that defines all my database params, as follows:
$db->host= "localhost";
$db->name= "mydatabase";
$db->user= "user";
$db->pw = "password";
The class is being instantiated correctly and the values show up in pages that appear after this class has been loaded.
BUT, when I try to connect to this database from a different class, it does not connect. Here's how I am connecting:
$dbconn = mysql_connect($db->host, $db->user, $db->pw);
mysql_select_db($db->name, $dbconn);
Everything works fine if I take out the user, pw and name variables and hard code in the correct values, but if any of them is referenced using the db construct, no connection happens. Again, the db construct appears just fine on other pages and I am seeing the variable values being presented correctly. The $db->host variable, however, always works.
Here's is how I am constructing the db class:
class database {
var $host;
var $name;
var $user;
var $pw;
function __construct($host = "localhost", $name = "mydatabase", $user = "user", $pw = "password"){
$this->host = $host;
$this->name = $name;
$this->user = $user;
$this->pw = $pw;
}
}
and then I of course do
$db = new database();
Thanks in advance for any help!
Don't use PHP4
Why don't you just use PDO
What's the point of storing password or username as a object property?
Probably the problem is a $db variable scope
How to fix all of that?
class MyClass {
protected $db;
public function __construct(PDO $db) {
$this->db = $db;
}
public function doSth() {
$this->db->query('..');
}
}
$db = new PDO('mysql:dbname=mydatabase;host=localhost', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$obj = new MyClass($db);
$obj->doSth();
I think u are not passing parameters when creating object for initializing the database class constructor.
try using
$db=new database("localhost","dbname","user","password");
and then create the class as
class database {
var $host;
var $name;
var $user;
var $pw;
function __construct($host , $name , $user , $pw ){
$this->host = $host;
$this->name = $name;
$this->user = $user;
$this->pw = $pw;
}
Also include this class as file if written separately
and for connection u can now write
$conn=mysql_connect($db->host,$db->user,$db->pw);
mysql_select_db($db->name,$conn);
Hope this helped :)
<?php
/*
link.php
Created By Nicholas English
*/
$link = null;
$connection = null;
$servername = "";
$username = "";
$dbname = "";
$pass = "";
$mysqli = null;
$pdo = null;
$obj = null;
$pr = null;
$type = 3;
if ($type === 1) {
$mysqli = true;
$pdo = false;
$obj = true;
$pr = false;
} else {
if ($type === 2) {
$mysqli = true;
$pdo = false;
$obj = false;
$pr = true;
} else {
if ($type === 3) {
$mysqli = false;
$pdo = true;
$obj = false;
$pr = false;
} else {
$mysqli = null;
$pdo = null;
$obj = null;
$pr = null;
}
}
}
if ($mysqli === true && $obj === true) {
$link = new mysqli($servername, $username, $pass, $dbname);
if ($link->connect_error) {
die("Connection failed: " . $link->connect_error);
}
$connection = true;
} else {
if ($mysqli === true && $pr === true) {
$link = mysqli_connect($servername, $username, $pass, $dbname);
if (!$link) {
die("Connection failed: " . mysqli_connect_error());
}
$connection = true;
} else {
if ($pdo === true && $mysqli === false) {
try {
$link = new PDO("mysql:host=$servername;dbname=$dbname", $username, $pass);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$connection = true;
}
catch(PDOException $e)
{
$connection = null;
echo "Connection failed: " . $e->getMessage();
}
} else {
$link = null;
$connection = null;
}
}
}
if ($connection == null && $link == null) {
$error = 1;
}
?>
Use mysqli or pdo for a more secure connection

"Undefined Variable" notice

Im new to php so im sure this is an easy one. Im getting this error
Notice: Undefined variable: conn in C:\Dev\Webserver\Apache2.2\htdocs\EclipsePHP\thecock\php\db.php on line 23
for this code
<?php
$host = "localhost"; $database = "dbname"; $username = "user"; $password = "pass";
$conn = new mysqli($host, $username, $password, $database);
if (! $conn) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}else{
echo("all ok!");
}
function getContent($id) {
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) { # line 23
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}
?>
How do I fix the notice?
Change your function to:
function getContent($id, $conn) {
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) {
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}
You don't declare the "original" $conn in the scope of the function. Inside the function you only have access to variables declared inside the function or provided via parameters.
Another way would be to declare the variable as global in your function:
function getContent($id) {
global $conn;
$sql = "SELECT content FROM blocktext WHERE id=$id";
if ($rs = $conn->query($sql)) {
if ($row = $rs->fetch_assoc()) {
echo stripslashes($row['content']);
}
$rs->close();
}
}
But you should only do this, if there is no other way. Globals make it hard to debug and maintain the code.
See also Variable scope and why global variables are bad.
Edit:
Yes e.g. you can have a DB class:
class DB {
private static $conn = null;
public static function getConnection() {
if (is_null(DB::$conn)) {
$host = "localhost"; $database = "dbname"; $username = "user"; $password = "pass";
DB::$conn = new mysqli($host, $username, $password, $database);
}
return DB::$conn;
}
}
Of course this is not the best implementation ;) But it should give you the right idea. Then you can get the the connection:
DB::getConnection()
conn is a global variable. To access it within a function:
function getContent($id) {
global $conn;
...
}
Otherwise the function can't see it.

Categories