3

I am creating a site which connects to database using public static function. As it is called by class name i can't understand how will i execute mysqli_query(). Below is the code:

db.class.php

<?php
class connect
{
    private static $db_host='localhost';

    private static $db_user='root';

    private static $db_pass='';

    private static $db_name='i_constuddoer01';

    //using public static function to avoid overloading
    public static function cxn_mysqli() {
        $result=mysqli_connect(self::$db_host,self::$db_user,self::$db_pass,self::$db_name);
        if(!$result)
            header("Location: sorry.php");
        else 
            return $result;
        }
    }
}

functions.php

<?php
require_once('db.class.php');

function addUser($fname,$lname,$email,$pass) {
    $query="INSERT INTO users VALUES(...)";
    $qr_status = mysqli_query(connect::cxn_mysqli(),$query)
}

What should I do, is there any other way?

1
  • Do you just want to use the existing connect class? Or are you writing this class and do you want feedback on this? Commented Jun 26, 2015 at 8:47

1 Answer 1

0

I think what your trying to do is create a singleton class, below is an example of one

class Connect
{
    private static $instance;

    # make the construct private to avoid anyone using new Connect()
    private function __construct()
    {
        # Sql connect code in here
    }

    static public function i()
    {
        if(!is_object(self::$instance)) {
            return new self;
        }
        return self::$instance;
    }
}

# Lets try to create two instances
$i = Connect::i();
$j = Connect::i();

# Oh look they are exactly the same object
echo spl_object_hash($i)."\n";
echo spl_object_hash($j)."\n";

Hope that helps

Sign up to request clarification or add additional context in comments.

1 Comment

Since mysqli has persistent connections by default, why should we use a singleton for mysqli?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.