Jump to content

Mysqli simplified class for dummies

Recommended Posts

Eyo all, been working on a website for a client and i got tired of writing thousands of functions to get out the data from DB. You know in this business you keep learning things while working on. My main issue was i could not dinamically add params to $stmt->bind_param, but after reading few hundreds lines on PHP mysqli doc i found out i can pass them dinamically by referrence and use the mighty call_user_func_array. However what i'm going to print is just a sample not the full class you've got to struggle yourself for other things. There must be many other ppl who want to learn PHP.

NOTE!!! The class i'm sharing is incomplete it only have a single function and is jut for learning purpose, you'll have to figure out yourself the rest.

class mmlDatabase{
    private $database = array("host" => "", "username" => "root", "password" => "ascent", "database" => "mydatabase");
    //Why public? easy like this you can call the function outside the class and print the error wherever you want
    public $errors = array();
	    private function connect()
        $con = mysqli_connect($this->database['host'], $this->database['username'], $this->database['password'], $this->database['database']);
        if (!$con) {
            printf("Connect failed: %s\n", mysqli_connect_error());
        return $con;
	    public function Query($sql='', $input_params = array(), $param_types = '', $getoutput = false){
        $sql = Represent the raw sql text whith questionmark as values
        $input_params = Represent the array of values that need to be inserted
        $param_types = Represent the type of parameters, s = string, i = integer, d = double,  b = blob
        $getoutput = If you are waiting for an output after a SELECT QUERY
        $output = array();
        $params = array();
        $conn = $this->connect();
	        $n = strlen($param_types);
        //Adding param types as first variable ("param types", waiting for params)
        $params[] = & $param_types;
	        //Adding Params one by one as referrence
        for($i = 0; $i < $n; $i++)
            $params[] = & $input_params[$i];
	        //Try to run query otherwise throw error
        if($stmt = $conn->prepare($sql)) {
            //Now calling bind param as user function passing the new parametter list
            call_user_func_array(array($stmt, 'bind_param'), $params);
            //check if we are waiting for a response (array of variables) mostly for SELECT query
            if($getoutput) {
                $result = $stmt->get_result();
                while ($data = $result->fetch_assoc()) {
                    array_push($output, $data);
            array_push($this->errors, 'Wrong SQL: ' . $sql . ' Error: ' . $conn->errno . ' ' . $conn->error);
	        //Return the output if there's no errors else return false and print the error wherever you want
        if(count($this->errors) === 0 && !empty($output))
            return $output;
        return false;
	$DB = new mmlDatabase;
$result = $DB->Query("SELECT * FROM `mytable`", NULL, NULL, true);
$result = $DB->Query("SELECT * FROM `mytable` WHERE `column` = ?", array(1), "i", true);
$result = $DB->Query("SELECT * FROM `mytable` WHERE `name` = ? AND `id` = ?", array("Some Name", 1), "si", true);
	$DB->Query("INSERT INTO `mytable`(`name`, `email`, `password`, `age`) VALUES (?, ?, ?, ?)", array("Some Name", "Some Email", "password", 23), "sssi", false/*can leave this variable blank since by default is false*/);
$DB->Query("REPLACE INTO `mytable`(`id`, `name`, `email`, `password`, `age`) VALUES (?, ?, ?, ?, ?)", array(1, "Some Name", "Some Email", "password", 23), "isssi", false/*can leave this variable blank since by default is false*/);
$DB->Query("UPDATE `mytable` SET `name` = ? WHERE `id` = ? AND `email` = ?", array("newname", 1, "email"), "sis", false/*can leave this variable blank since by default is false*/);
	//Separate variables sent inside query
	$sql = "INSERT INTO `mytable`(`name`, `email`, `password`, `age`) VALUES (?, ?, ?, ?)";
$params = array(1, "Some Name", "Some Email", "password", 23);
$param_types = "sssi";
$DB->Query($sql, $params, $param_types, false);

Share this post

Link to post
Share on other sites
2 hours ago, OMGhixD said:

Thank you for this task :D

trust me this **** saved my life usually i had to write hundred of lines of codes but now i've learned my lesson :)) hopefuly this will be helpful for somebody else because as of now i could only find huge ass overwrites of the class and most of them were for Wordpress pretty hard to reintegrate on a fresh built website 

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

About us

MMO-Society is the Forum former known as Lordcraft, MMO-Society offers various of Resources to help you evolve your knowledge within Emulation, In the process we make sure to form a strong community bond in-between each other and thus we are proud to can admit that MMO-Society is possibly the friendliest Community Forum to currently exist.

Useful Quick-Links

  • Create New...