How to use mysqli _construct with database connection

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Tuyet
    New Member
    • Aug 2010
    • 3

    #1

    How to use mysqli _construct with database connection

    I am attempting to connect to the database (which was successfully). However, I can not extend the connection to execute other functions. In my example below,
    the output is not giving me what I expected. There seem to be two connections and my escaped text which I called ($data = $query->select($text); ) does not execute.

    OUTPUT:
    Connection established! Now:Connection established! Now:
    text passed =Brian O'Dell
    text can be escaped =


    INDEX.PHP (main page):

    Code:
    include("database_connect.php");
    include("query_builder.class.php");
    
    $text = "Brian O'Dell";
    
    $query = new QueryBuilder;
    $data = $query->select($text);

    DATABASE_CONNEC T.PHP:

    Code:
    public $host = 'localhost';
    public $db_username = 'root';
    public $db_password = 'password';
    public $db_name = 'customer';
    
    protected $mysqli;
    
    public function __construct() {}
    
    public function connect()
    {
    $this->mysqli = new mysqli($this->host,$this->db_username,$this->db_password,$this->db_name);
    
    if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '. $mysqli->connect_error);
    }		
    else
    {
    echo "Connection established! Now:";
    }
    
    } 
    
    public function db_close()
    {
    $this->mysqli->close();
    } 
    
    public function __destruct() {}

    QUERY_BUILDER.C LASS.PHP:

    Code:
    class QueryBuilder
    {
    
    public function __construct()
    {
    	$this->connect = Db_Connect::connect();	
    }
    
    public function __destruct()
    {
    	Db_Connect::db_close();
    }
    
    public function select($sql=false)
    {
    	
    	echo "<br>text passed =".$sql."<br>";
    	$newtxt =  $this->mysqli->real_escape_string($sql);
    	echo "text can be escaped = ".$newtxt;
    
    }
    }
    Last edited by Dormilich; Aug 30 '10, 05:26 PM. Reason: Please use [code] tags when posting code
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    as far as I can see, you don’t have a $this->mysqli instance. $this->connect is null (Db_Connect::con nect() doesn’t return anything) and I guess Db_Connect should be a Singleton (though it’s currently called incorrectly (in static context)).

    … I’d probably find more issues if I see the whole code

    Comment

    Working...