简体   繁体   中英

How do I make this “database connection” code more efficient to run?

I have this code:

 function Perubahan($a = '`Ubah`') {
        $con = mysqli_connect("localhost", "root", "", "nofriani"); //koneksi ke database

        $syntax = 'SELECT' . $a . ' FROM `table 1` WHERE `No`= 6';
        $naik = mysqli_query($con, $syntax);
        while ($row = mysqli_fetch_array($naik)) {
            echo round($row[0], 3);
        }
    }

    function Jenis($b = 1) {
        $con = mysqli_connect("localhost", "root", "", "nofriani"); //koneksi ke database

        $syntax = 'SELECT `Jenis` FROM `table 1` WHERE `No`= ' . $b;
        $naik = mysqli_query($con, $syntax);
        while ($row = mysqli_fetch_array($naik)) {
            echo $row[0];
        }
    }

    function Andil($b = 1) {
        $con = mysqli_connect("localhost", "root", "", "nofriani"); //koneksi ke database

        $syntax = 'SELECT `Andil` FROM `table 1` WHERE `No`= ' . $b;
        $naik = mysqli_query($con, $syntax);
        while ($row = mysqli_fetch_array($naik)) {
            echo round($row[0], 3);
        }
    }

    function Kelompok($b = 1) {
        $con = mysqli_connect("localhost", "root", "", "nofriani"); //koneksi ke database

        $syntax = 'SELECT `Andil` FROM `table 1` WHERE `No`= ' . $b;
        $naik = mysqli_query($con, $syntax);
        while ($row = mysqli_fetch_array($naik)) {
            echo round($row[0], 3);
        }
    }

So I call each function (still in the same PHP file). But when I start running it, it took too long to show the result (but it worked). I'm guessing the problem is because I repeat the database connection in each function. How do I make avoid connecting to the same database?

I tried to create the database connection to different file and call the file in each function, but it didn't work. I also tried to pass the $con variable into the function (doing global $con in each function), but it also didn't make it run faster.

So am I missing something here?

You can use a class:

class NameService
{
    private $con = null;

    public function __construct()
    {
        $this->con = new mysqli("localhost", "root", "", "nofriani");
        if ($this->con->connect_error) {
            die('Connect Error (' . $this->con->connect_errno . ') '
             . $this->con->connect_error);
        }
    }

    public function __destruct()
    {
        $this->con->close();
    }

    function Andil($b = 1) {
        $syntax = 'SELECT `Andil` FROM `table 1` WHERE `No`= ' . $b;
        $result= $this->con->query($syntax);
        while ($row = $result->fetch_array()) {
            echo round($row[0], 3);
        }
    }

    ...
}

and use it:

$nameService = new NameService();
$nameService->Andil(23);

EDIT: now it's with OOP style

If you can use Classes, than you can create global variable for class, that holds connection to database, than each function will use same connection and there will be no reconnect.

Use prepared statements, because now your code is very easy to hack.

Functions Jenis , Andil and Kelompok does exactly same as Perubahan that is prepared for core reuse, so just rename it to getData($select = '*') and use only one function.

As a rule of DRY you'd better extract this part of code :

mysqli_connect("localhost", "root", "", "nofriani"); //koneksi ke database

and put in one place (a class or a function)where all other codes can access it. For example you can have a function like this :

function getConnection()
{
return mysqli_connect("localhost", "root", "", "nofriani"); //koneksi ke database
}

And then you can do something like this :

function Jenis($b = 1) {
        $con = getConnection();

        $syntax = 'SELECT `Jenis` FROM `table 1` WHERE `No`= ' . $b;
        $naik = mysqli_query($con, $syntax);
        while ($row = mysqli_fetch_array($naik)) {
            echo $row[0];
        }
    }

This way if your ConnectionString is changed you should change one place and all other functions work as before.(BTW it's better not to hard code the ConnectionString )

    global $con;
    // Requires a password here...
    $con = new PDO('mysql:host=localhost;dbname=nofriani', 'root', $pass);

    class   QueryEngine
        {
            public  function Fetch($_sql)
                {
                    global $con;
                    // You could bind values here
                    $query  =   $con->prepare($_sql);
                    $query->execute();

                    if($query->rowCount() > 0) {
                            while($result = $query->fetch(PDO::FETCH_ASSOC)) {
                                    $array[]    =   $result;
                                }
                        }

                    return (isset($array))? $array:0;
                }
        }

    class   NameEngine
        {
            protected   $MySQL;
            public  function __construct()
                {
                    // Create sql engine object
                    $this->MySQL    =   new QueryEngine();
                }

            public function execute($_name = false,$_value = 1) {
                    // If the name is not blank, run
                    if($_name !== false) {
                            // Fetch values to array (or do your round() function)
                            // I tend to just return arrays in classes and loop the array on an html page but you could do your echo here too.
                            $_result    =   $this->MySQL->Fetch("SELECT $_name FROM `table 1` WHERE `No`= '$value'");
                        }

                    // If name not set, just return empty/false
                    return (isset($_result))? $_result:0;
                }
        }

    // Create name object
    $_FetchNames    =   new NameEngine();
    // Run name(s)
    $_Jenis         =   $_FetchNames->execute('Jenis');
    // Print result
    print_r($_Jenis);
    // Close connection
    $con    =   NULL;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM