简体   繁体   English

如何使此“数据库连接”代码更有效地运行?

[英]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). 所以我调用了每个函数(仍然在同一个PHP文件中)。 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. 我还尝试将$ con 变量传递给函数 (在每个函数中执行global $con ),但它也没有使其运行得更快。

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 编辑:现在它具有OOP风格

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. 如果可以使用Classes,则可以为类创建全局变量,该全局变量保存与数据库的连接,然后每个函数将使用相同的连接,并且不会进行重新连接。

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. 功能JenisAndilKelompok不作为完全相同Perubahan是核心重用准备,所以只是将其重命名为getData($select = '*')并且只使用一个功能。

As a rule of DRY you'd better extract this part of code : 作为DRY的规则,您最好提取这部分代码:

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 ) 这样,如果您的ConnectionString被更改,则您应该更改一个位置,所有其他功能都像以前一样工作。(顺便说一句,最好不要对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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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