Sunday, October 10, 2010

Php Mysqli extension

The MySql Improved Extension, a.k.a mysqli is faster more improved version of existing mysql. It is available in PHP 5 or later versions. The source code of mysqli is available at ext/mysqli. For further information click here.
A simple example how to connect and insert temp data to database 'mydb' and table 'mytable'.
Lets add DbConnector.php first,

<?php
class DbConnector {

    private $db_host;
    private $db_user;
    private $db_pass;
    private $db_name;
    private $connection;

    public function __construct($host = '127.0.0.1', $user = 'root', $pass='', $database_name='mydb') {
        $this->db_host = $host;
        $this->db_user = $user;
        $this->db_pass = $pass;
        $this->db_name = $database_name;
    }

    public function connectDb() {
        $this->connection = mysqli_connect($this->db_host, $this->db_user, $this->db_pass) or die(mysqli_error());
        mysqli_select_db($this->connection, $this->db_name) or die(mysqli_error());
    }

    public function closeConn() {
        if ($this->connection) {
            mysqli_close();
        }
    }

    public function isConnected() {
        if ($this->connection) {
            return true;
        } return
        false;
    }

    public function execute_query($sql) {
        if (!$this->isConnected()) {
            $this->connectDB();
        }
        $result = mysqli_query($this->connection, $sql) or die(mysqli_errno($this->connection));
        return $result;
    }


    public function get_query($sql) {
        if(!$this->isConnected()) {
            $this->connectDb();
        }
        $result = mysqli_query($this->connection, $sql) or die(mysqli_errno($this->connection));

        $resultArray = array();
        $count = 0;
        while ($obj = mysqli_fetch_object($result)) {
            $resultArray[$count] = $obj;
            $count++;
        }
        return $resultArray;
    }
}
?>


Now add MyTable.php Class which represents the 'mytable' database table.

<?php

include_once 'DbConnector.php';

class MytableTable {

    private $dbConn;

    public function __construct() {
        $this->dbConn = new DbConnector();
    }

    public function insertNew($val) {
        $sql = "insert into mytable (col)" .
                " values ('$val') ";
        return $this->dbConn->execute_query($sql);
    }

    public function getMytableAll(){
        $sql = "select * from mytable";
        return $this->dbConn->get_query($sql);
    }
}
?>

Now from your interface you can use the above two php class to add a new entry in mytable or get all the entries from mytable.



0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...