Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am self learning php and trying oop, I am struggling with following problem, Would anyone could help me how can I use following database connection in to another class function. In php.net it is defined as $mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db'); but when I use this within a class it dose not work. Thanks

class dbconnect{
private $host;
private $user;
private $pass;
private $dabase;

function doConnect()
{
    $this->host = 'localhost';
    $this->user = 'root';
    $this->pass = 'abc@123';
    $this->dabase = 'database_5';

    $db = new mysqli($this->host, $this->user, $this->pass, $this->dabase);

    if (mysqli_connect_errno())
    {
        echo "<br /><hr />";
        echo "<p style='align:center;'>Error : could not connect to database.. </p>";
        echo "<hr />";
        exit;
    } 
}   
$mysql = new dbconnect();
function doQuery($mysql){
     $queryUser = $mysql->query("SELECT * FROM b_admin_user WHERE username_d = 'admin'");
     echo $queryUser_row = $queryUser->num_rows;
} 
doQuery($mysql);
share|improve this question
    
Try returning $db inside doConnect(), and call it in the constructor, or call $mysql = $mysql->doConnect() –  1nflktd Jul 6 at 13:25
1  
mysqli_connect_errno() is procedural style. Check $db->connect_errno(). –  GolezTrol Jul 6 at 13:46
1  
What is your intent in building this class? It does not seem like are are providing any meaningful abstraction or additional functionality beyond just using OO native mysqli class. Also I am not sure if this is code example is snippets of code throughout the class, but you can't have arbitrary executable code being executed outside of a function scope in a class. –  Mike Brant Jul 6 at 14:02

1 Answer 1

Try this

   <?php
   class MySQL {

   //objekto kintamieji
   private $host;  
   private $username;
   private $password;
   private $database;
   private $conn;  // connection

   public function __construct($set_host, $set_username, $set_password){
    $this->host = $set_host;
    $this->username = $set_username;
    $this->password = $set_password;
    // jungiuosi prie db
    $this->conn = mysql_connect($this->host, $this->username, $this->password)
                  or die("Couldn't connect");
   }

   public function database($set_database)
   {   
    $this->database=$set_database;
    //pasirenku lentele
    mysql_select_db($this->database, $this->conn) or die("cannot select Database");
   }

   }
   // jungiames
   $connect = new MySQL('localhost','root','');
   $connect->database('job');

   ?>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.