Do mysql functions open a new mysql connection if no mysql link is specified?

Are there functions such as mysql_query, mysql_real_escape or mysql_error to open a new mysql link if it is not specified?

php.net says that

MySQL connection. If no link identifier is specified, it is assumed that the last link opened by mysql_connect (),

But what if the connection was made inside the class? Php knows how to find this link?

(I use the codeigniter framework if any help)

+4
source share
1 answer

, Singleton , "". , . , , , mysql_query, , , , .

[ ]

, - :

    //Database.class.php

    class Database {
        public function connect_db() {
             //connection logic here
        }

        public static function query_db($query) {
             $this->connect_db();
             //query database logic here
        }

    }


    //index.php
    include "path/to/Database.class.php";

    $sql = "SELECT * FROM `whatever_i_want`";
    Database::query_db($sql);

    //repeat the last two lines multiple times

. . , :

    //Database.class.php
    public function __construct() {
         $this->connect_db();
    }

    public function query_db($query) {
          //query database logic here
          //note the missing call to connect_db()
    }
    //the rest remains unchanged

    //index.php
    $db = new Database();

    $db->query_db($sql);
    //the rest remains unchanged

, , , , , . , , PHP , . , , , , , .

, index.php:

    //index.php
    $db2 = new Database();

    $db2->query_db($sql);
    $db->query_db($sql);

, $db2, , PHP.

+2

Source: https://habr.com/ru/post/1525173/


All Articles