Travis Pessetto Travis Pessetto - 1 month ago 6
PHP Question

My function always returns a boolean value instead of query results

I have an application that reads in one of its classes:

public function __construct()
{
global $config;
//Establish a connection to the database and get results set
$this->db = new Database("localhost",$config["dbuser"],$config["dbpass"],"student");
$this->records = $this->db->query("SELECT * FROM major") or die("ERROR: ".$this->db->error);
echo "<pre>".var_dump($this->records)."</pre>";
}


My problem is that
var_dump shows
that
$this->records
is a boolean. I've read the documentation and see that the SELECT query should return a result set. This is the only query used by the application.

The DB Class:

class Database
{
private $con;

public function __construct($server,$user,$password,$database)
{
$this->con = new mysqli($server,$user,$password,$database) or die ("FATAL ERR: ".mysqli_error());
}

public function query($qry)
{
if(!isset($this->con)) die("ERROR: YOU ARE TRYING TO QUERY BEFORE THE CONNECTION IS ESTABLISHED!");
return $this->con->query($qry) or die("FATAL ERROR:".$this->con->error);
}
}


Any ideas where I am going wrong?

Answer

This answer is wrong, but cannot be deleted (because it is accepted).

This is expression:

$this->db->query("SELECT * FROM major") or die("ERROR: ".$this->db->error);

that returns true.

Split it to actual query and check:

$this->records = $this->db->query("SELECT * FROM major");
if(!$this->records){
     //show some error
}

the same applies to your database class, it returns boolean result because of or operator.

Comments