I have the code below.... it doesnt work except when i mover the db connection inside the function......
can anyone assist?
<?php
class user{
@ $db= new mysqli("localhost","usernae","password", "database");
if (mysqli_connect_errno()){
echo "not connected";
}
function get_name($ssid){
$db= $this->db;
$query="select * from table where id='$ssid'";
$result=$db->query($query);
if(($result->num_rows)==1)
{
$row=$result->fetch_object();
$fname=$row->firstName;
$lname=$row->lastName;
$fullname= ucwords($fname. " ".$lname);
return $fullname;
}
}
}
?>
Database connection problem
Moderator: General Moderators
Re: Database connection problem
Read more about classes... you can't have executable code in the class declaration, only in it's methods
However there is a special method, that's is called automatically when you are creating a new instance. It's called constructor:
However there is a special method, that's is called automatically when you are creating a new instance. It's called constructor:
Code: Select all
<?php
class user{
protected $db;
public function __construct()
{
$this->db = new mysqli("localhost","usernae","password", "database");
if (mysqli_connect_errno()){
echo "not connected";
}
}
public function get_name($ssid){
$db= $this->db;
$query="select * from table where id='$ssid'";
$result=$db->query($query);
if(($result->num_rows)==1)
{
$row=$result->fetch_object();
$fname=$row->firstName;
$lname=$row->lastName;
$fullname= ucwords($fname. " ".$lname);
return $fullname;
}
}
}
Re: Database connection problem
great! thanks!