drxyaox153896 2019-08-19 17:03
浏览 183
已采纳

如何使用PHP函数使用PDO连接到MySQL [关闭]

I'm using this method to connect to my MySQL db to SELECT, INSERT, UPDATE and DELETE data. This is the cnn() function:

function cnn() {
    static $pdo;
    if(!isset($pdo)) {
        $settings = [
            PDO::ATTR_TIMEOUT => 30,
            PDO::ATTR_PERSISTENT => false,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ];
        try {
            # settings
            $config['db']['host'] = 'example.com';
            $config['db']['name'] = 'db';
            $config['db']['user'] = 'username';
            $config['db']['pass'] = '****************';
            $pdo = new PDO('mysql:host='.$config['db']['host'].';dbname='.$config['db']['name'], $config['db']['user'], $config['db']['pass'], $settings);
            return $pdo;
        } catch(PDOException $e) {
            http_response_code(503);
            echo $e->getCode().': '.$e->getMessage();
        }
    } else {
        return $pdo;
    }
}

And then i can just do this to re-use the same pdo object each time i need it on the same request.

1st query

$sql = 'INSERT INTO user (name, lastname) VALUES (:name, :lastname)';
$stmt = cnn()->prepare($sql);
$stmt->bindValue(':name', "John", PDO::PARAM_STR);
$stmt->bindValue(':name', "Wayne", PDO::PARAM_STR);
$stmt->execute();

2nd query

$sql = 'SELECT * FROM user WHERE id_user = :id_user';
$stmt = cnn()->prepare($sql);
$stmt->bindValue(':id_user', 4641, PDO::PARAM_INT);
$stmt->execute();
$user = $stmt->fetch();

I was wondering if there could be any performance issues by using this approach. Thanks.

  • 写回答

1条回答 默认 最新

  • dsdt66064367 2019-08-19 17:40
    关注

    1)

    As referenced by HTMHell, your $config array is local here and I believe this should be deleted after use so password variables are not leakable on a later get_defined_vars() call, or similar cross reference.

    2)

    It seems far more logical to me to put your function in a class. Run the cnn() function from the __construct. There are a lot of positive aspects to wrapping this function in a full class.

    3)

    Do NOT set any variable to being static unless you have a specific requirement in the context of putting your cnn() function into a Class.

    4)

    Correctly use your try{ ... } catch { ... } blocks, do not wrap other code in the try block except code that throws exceptions.

        // settings
        $config['db']['host'] = 'example.com';
        $config['db']['name'] = 'db';
        $config['db']['user'] = 'username';
        $config['db']['pass'] = '****************';
        try {
            $pdo = new PDO('mysql:host='.$config['db']['host'].';dbname='.$config['db']['name'], $config['db']['user'], $config['db']['pass'], $settings);
        } catch(PDOException $e) {
            /***
             * Do you really need this, here?  
             * //http_response_code(503);
             **/
            echo $e->getCode().': '.$e->getMessage();
        }
        return $pdo;
    

    5)

    DO NOT EVER OUTPUT ERRORS DIRECTLY TO THE SCREEN

    Errors should be logged so only server folks and developers rather than the general public can see them. This also means you have a log of errors rather than a single, temporary instance of any that occur.

    echo $e->getCode().': '.$e->getMessage(); Should be:

    error_log($e->getCode().': '.$e->getMessage());
    

    Or similar. Stay consistent; always return a PDO object and not echo outputs.

    6)

    Remove your final else wrapper it is merely clutter.

    if(!isset($pdo)) {
         ...
    } 
    return $pdo; 
    

    Also remove the return $pdo; inside your try { ... } block. Don't Repeat Yourself.

    7)

    Properly document your code:

    /***
     * For generating or asserting a PDO Database Object.
     * @return Returns the PDO object 
     ***/
     function cnn() {
    

    To answer the question you actually asked:

    I was wondering if there could be any performance issues by using this approach.

    This question is far too broad and can be solved by yourself using timer testings or other methods (detailed in the link) to establish on your system if it is particularly efficient or inefficient, or what SQL you choose to give it...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Stata链式中介效应代码修改
  • ¥15 latex投稿显示click download
  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 添加组件无法加载页面,某块加载卡住
  • ¥15 网络科学导论,网络控制
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错