Goodday,
I get an strange error.
this is my code:
<?php
$con=mysqli_connect("localhost","root","","testdatabase");
class database{
public function select($tableName){
$result = mysqli_query($con,"SELECT * FROM ".$tableName);
}
}
$database = new database();
?>
The error message is that $con is an undefined variable. But i define $con on line number 2?
when i var_dump con it also says NULL.
What am i doing wrong?
If you want to access to your $con var in a method or function, you have to globalize it inside your code :
public function select($tableName){
global $con;
$result = mysqli_query($con,"SELECT * FROM ".$tableName);
}
But you shouldn't do that, globals are evil !
This is how your code should be :
<?php
class database{
protected $con;
public function __construct($host, $user, $password, $dbname){
$this->con = mysqli_connect($host, $user, $password, $dbname);
}
public function select($tableName){
$result = mysqli_query($this->con,"SELECT * FROM ".$tableName);
}
}
$database = new database("localhost", "root", "", "testdatabase");
?>
The connection $con
is available in the global scope. What you likely want to do is inject your mysql connection (in the form of mysqli object) in the constructor for your Database object. Here is a simple example:
<?php
$mysqli= new mysqli("localhost","root","","testdatabase");
class database{
protected $mysqli = null;
public function __contruct(MySQLI $mysqli = NULL) {
$this->mysqli = $mysqli;
}
public function select($tableName){
$result = $this->mysqli->query("SELECT * FROM ".$tableName);
}
}
$database = new database($mysqli);
?>
Note that since you are trying to go with an object-oriented paradigm, you might as well use mysqli in an object oriented fashion.
Add a construct function to your class and declare your connection inside this function.
class database{
private $con;
public function __construct(){
$this->con=mysqli_connect("localhost","root","","testdatabase");
}
public function select($tableName){
$result = mysqli_query($this->con,"SELECT * FROM ".$tableName);
}
}
$database = new database();
You can't use global variables inside a class.
<?php
class database {
private $con;
public $result;
public function select($tableName){
$this->con = mysqli_connect("localhost","root","","testdatabase");
$this->result = mysqli_query($this->con,"SELECT * FROM ".$tableName);
}
}
$database = new database();
// do something with result
if($database->result) {
echo "Query returned something!";
}
?>