Database connection problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
vonnero
Forum Newbie
Posts: 17
Joined: Tue Feb 17, 2009 6:19 am

Database connection problem

Post by vonnero »

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;
}
}


}






?>
User avatar
Darhazer
DevNet Resident
Posts: 1011
Joined: Thu May 14, 2009 3:00 pm
Location: HellCity, Bulgaria

Re: Database connection problem

Post by Darhazer »

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:

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;
     }
}
 
}
 
vonnero
Forum Newbie
Posts: 17
Joined: Tue Feb 17, 2009 6:19 am

Re: Database connection problem

Post by vonnero »

great! thanks!
Post Reply