I have two php classes, in two files.
....db.php ....sql.php
db contains:
class DataBase {
private $link;
private $host;
private $username;
private $password;
private $database;
public function __construct() {
print'<br>in constructor DB!<br>';
$this->host = 'xxxx';
$this->username = 'xxxx';
$this->password = 'xxxx';
$this->database = 'xxxx';
$this->connect();
}
public function connect() {
$this->link = mysql_connect($this->host,$this->username,$this->password);
if (!$this->link) die('Could not connect: ' . mysql_error());
mysql_select_db($this->database, $this->link);
}
public function getConnection() {
return $this->link;
}
}
sql.php contains :
include 'db.php';
class SQL {
public $dataBase;
public $con;
public function __construct() {
$dataBase = new DataBase;
print 'database -> '.$dataBase;
$con = $dataBase->getConnection();
}
public function login($email, $pass) {
$sql = "SELECT * FROM clienti WHERE email='".$email."' and pass= md5('".$pass."')";
$result = mysql_query($sql, $con) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if(!$row) return 'Email or password is incorrect.';
return '';
}
}
in login.php
<?php
include 'include/sql.php';
$email = $_GET['email'];
$pass= $_GET['pass'];
$error = '';
if($email == '' || $pass== '') {
$error = 'Email or password is empty.';
}
else {
$sql = new SQL(); //if I print inside constructor, $con variable, is something like #3 resources
echo $sql->con; // but here is empty ???
$sql->login($email, $pass);
$sql->close();
}
What I am doing wrong?
The includes are ok, I tested them. But why variables of sql Object are empty??? thank you.
$con
is a property of the class not a variable, you refer to it by using keyword $this
:
$con = $dataBase->getConnection(); //WRONG
change to:
$this->con = $dataBase->getConnection(); //CORRECT
You forgot ()
So try this:
$dataBase = new DataBase();
Also it could be that you get following error:
Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
So i would recommend you to rewrite your code to PDO
or mysqli
BTW:
For error reporting use:
<?php
ini_set("display_errors", 1);
error_reporting(E_ALL);
?>
You have $con
listed as private, so you can't access it from outside the class, like $sql->con
. If you need to use it like $sql->con
, change this in SQL.php:
private $con;
to this:
public $con;
Based on one of your comments though, your issue may simply be that you need to use $this->con
instead of just $con
in the methods of your SQL class.