简体   繁体   中英

Php - using include/require_once inside function

I am creating a class " DBQuery " that contains all the database query functions such as insert, select, delete, ...

Everything is working fine when I create database connection inside the INSERT function. But i want separate the configuration so that i can include it in any other files and pages.

configuration.php

define("HOSTNAME", "localhost");
define("USERNAME", "root");
define("PASSWORD", "");
define("DATABASE", "edubits");

try {
    $conn = new PDO("mysql:host=" . HOSTNAME . ";dbname=" . DATABASE . ";", USERNAME, PASSWORD);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    echo $e;
}

class.php

/**
 * Created by PhpStorm.
 * User: Sunusi Mohd Inuwa
 * Date: 11/18/2018
 * Time: 11:02 AM
 */
class QUERY
{
    function INSERT($table, $data, $conn)
    {
        include_once('../configuration.php');

        // variable declaration
        $columns = "";
        $valueset = "";
        $values = "";

        //loop
        foreach ($data as $column => $value) {
            $columns = $columns . ', ' . $column;
            $valueset = $valueset . ', ?';
            $values = $values . ', ' . $value;
        }

        //trimming the first comma from the result above
        $columns = ltrim($columns, ',');
        $valueset = ltrim($valueset, ',');
        $values = ltrim($values, ',');

        //statement
        $sql = "INSERT INTO " . $table . "(" . $columns . ") VALUES(" . $valueset . ")";

        //convert values to array
        $values = explode(',', $values);

        //query
        $query = $conn->prepare($sql)->execute($values);
        //$query = $conn->prepare($sql)->execute([$values]);;


    }
}

Use include , not include_once . If you use include_once , then it won't execute the code in the file the second time you call the method.

But it would probably be better to include the file in the class's constructor, so you only need to execute it once, rather than create a new connection every time you perform a query. Make $conn a class property instead of an ordinary variable.

The class below give the ability to get a connection object from getInstance() funtion, so you just include the Config class where you wanna communicate with database ( model )

getInstance() : is singleton, which means that you have a single instance

class Config{

    private $HOSTNAME = "localhost";
    private $USERNAME = "root";
    private $PASSWORD = "";
    private $DATABASE = "edubits";
    private static $pdo = null;

    public static function getInstance($data = null){
        if(self::$pdo == null){
            self::PDOConnect($data = null);
        }
        return self::$pdo;
    } 

    private static function PDOConnect(){
        try{
            $info = new DBInfo($data);
            self::$pdo = new PDO("mysql:host=" . $this->HOSTNAME . ";dbname=" . $this->DATABASE . ";", $this->USERNAME, $this->PASSWORD);
            self::$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            self::$pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
        } catch (PDOException $e) {
            echo new PDOCustomException($e->getMessage(), null, $e);
        }
    }

    public function close(){
        return null;
    }
}

Here i've choice to use config directly from your INSERT function to get connection object, or get connexion object in constructor one time and use it many time in QUERY class

So connection instance is stored on $cn

include_once('../configuration.php');

class QUERY
{
    private $cn = null;
    private $DBAction = null;

    public function __construct(){
        try {
            $cn = new DBAction();
            $this->cn = $cn::getInstance();
        } catch (\PDOException $ex) {
            throw new PDOCustomException($ex->getMessage(), null, $ex);
        } catch (\Exception $ex) {
            throw new CustomException($ex->getMessage(), null, $ex);
        }
    }

    public function INSERT($table, $data, $conn) {
        $config = new Config();

        // variable declaration
        $columns = "";
        $valueset = "";
        $values = "";

        //loop
        foreach ($data as $column => $value) {
            $columns = $columns . ', ' . $column;
            $valueset = $valueset . ', ?';
            $values = $values . ', ' . $value;
        }

        //trimming the first comma from the result above
        $columns = ltrim($columns, ',');
        $valueset = ltrim($valueset, ',');
        $values = ltrim($values, ',');

        //statement
        $sql = "INSERT INTO " . $table . "(" . $columns . ") VALUES(" . $valueset . ")";

        //convert values to array
        $values = explode(',', $values);

        //query
        $query = $this->cn->prepare($sql)->execute($values);

   }
}

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