mysql - Php mysqli database connection fail? -
goodday,
i strange error.
this code:
<?php $con=mysqli_connect("localhost","root","","testdatabase"); class database{ public function select($tablename){ $result = mysqli_query($con,"select * ".$tablename); } } $database = new database(); ?>
the error message $con undefined variable. define $con on line number 2?
when var_dump con says null.
what doing wrong?
if want access $con var in method or function, have globalize inside code :
public function select($tablename){ global $con; $result = mysqli_query($con,"select * ".$tablename); }
but shouldn't that, globals evil !
this how code should :
<?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 * ".$tablename); } } $database = new database("localhost", "root", "", "testdatabase"); ?>
Comments
Post a Comment