PHP-在函数内部使用include / require_once

时间:2018-11-19 09:17:07

标签: php

我正在创建一个类“ DBQuery ”,其中包含所有数据库查询功能,例如插入,选择,删除,...

当我在 INSERT 函数中创建数据库连接时,一切工作正常。但是我想分开配置,以便可以将其包含在任何其他文件和页面中。

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]);;


    }
}

2 个答案:

答案 0 :(得分:3)

使用include,而不是include_once。如果您使用include_once,那么它将在您第二次调用该方法时不执行文件中的代码。

但是将文件包含在类的构造函数中可能会更好,因此您只需要执行一次,而不是每次执行查询时都创建一个新的连接。将$conn设为类属性,而不是普通变量。

答案 1 :(得分:0)

下面的类使您能够从 getInstance()函数中获取连接对象,因此您只需要包含要与数据库进行通信的Config类(模型

getInstance():是单例,这意味着您有一个实例

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;
    }
}

这里,我选择直接从 INSERT 函数中使用config来获取连接对象,或者一次在构造函数中获取connexion对象,然后在QUERY类中多次使用它

因此,连接实例存储在 $ 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);

   }
}