php/pdo/mysql多DB调用最佳实践

标签 php mysql pdo

到目前为止,在回顾我的脚本时,我意识到我使用了两种不同的方法来检索/更新数据:在 try/catch 或多个 try/catch 中多次调用每个人一个电话。

无论使用哪种方法,我的测试数据的结果看起来都不错,但我想固定在生产环境中使用的最佳实践,因为测试数据不是真实的。例如,我想知道在 try/catch 中的多次调用中是否有可能得不到正确的异常。

在某些脚本上,我使用 try/catch 进行了 30 次 db 调用,使用了 30 个 open/close db,在其他脚本中,我使用了 6 个 进行了 30 次 db 调用使用 try/catch 打开/关闭数据库

谢谢。

示例方法一

try {
    $connexion = new PDO("mysql:host=$serveur;dbname=$db;charset=$charset", $login, $pwd);
    $connexion -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    select table1 / execute / process
    join table1 & table2 / execute / process
    update table3 / execute / process
    ...
    $connexion = null; // close

    } catch (PDOException $e) {
        echo "Connexion failed:".$e -> getMessage();
    }

示例方法 2

try {
    $connexion = new PDO("mysql:host=$serveur;dbname=$db;charset=$charset", $login, $pwd);
    $connexion -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    select table1 / execute / process

    $connexion = null; // close

    } catch (PDOException $e) {
        echo "Connexion failed:".$e -> getMessage();
    }

try {
    $connexion = new PDO("mysql:host=$serveur;dbname=$db;charset=$charset", $login, $pwd);
    $connexion -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    join table1 & table2 / execute / process

    $connexion = null; // close

    } catch (PDOException $e) {
        echo "Connexion failed:".$e -> getMessage();
    }

try {
    $connexion = new PDO("mysql:host=$serveur;dbname=$db;charset=$charset", $login, $pwd);
    $connexion -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    update table3 / execute / process

    $connexion = null; // close

    } catch (PDOException $e) {
        echo "Connexion failed:".$e -> getMessage();
    }

更新

我知道我做错了什么(我正在自学 PHP)。另一方面,我现在可以欣赏 Shudhansh Shekhar 和 e4c5 提出的解决方案的值(value)。

所以我构建了一个DBaccess类,我可以看到所有的优点。一个在脚本顶部包含一个新实例,您就快完成了。我在一个脚本上进行了测试,它运行得非常棒。

在我重新设计所有脚本之前,您能否验证我的代码?我不确定 $this->connexion = null; 是否位于关闭数据库的正确位置。

再次感谢您的帮助。

DBaccess.class.php

<?php
class DBaccess{
    private $serveur = "localhost";
    private $db_name = "qh61test";
    private $charset = "utf8";
    private $login = "root";
    private $pwd = "";

    private $connexion;   // dbh name
    private $erreur;
    private $requete;     // sql stmt

    public function __construct(){
        $this->connexion = null; // <-----------  NOT SURE ?
        try{
            $this->connexion = new PDO("mysql:host=" . $this->serveur . ";dbname=" . $this->db_name. ";charset=". $this->charset, $this->login, $this->pwd);
            $this->connexion->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  
        }
        catch(PDOException $e){
            echo "Connexion foirée :".$e -> getMessage();
            // $this->erreur = $e->getMessage();
        }
    }

    public function sql($sql){
        $this->requete = $this->connexion->prepare($sql);
    }
    public function execute(){
        return $this->requete->execute();
    }
    public function resultAll(){
        $this->execute();
        return $this->requete->fetchAll(PDO::FETCH_ASSOC);
    } 
}
?>

script.php

        <?php 
        session_start();
        include 'DBaccess.class.php';
        $db = new DBaccess();
        ...
        if (isset($_POST['periode'])) { 

            // sales within a period
            if (!empty($_POST['datebeg']) && !empty($_POST['dateend'])) {

               // datepicker dates
               $datebeg = preg_replace("([^0-9/])", "", $_POST['datebeg']);
               $dateend = preg_replace("([^0-9/])", "", $_POST['dateend']);

            $search_row = "SELECT COUNT(cmdID) as nbcmd FROM Commande2 WHERE date_cmd BETWEEN '$datebeg' AND '$dateend'"
            );

                $db->sql("$search_row"); 
                $db->execute();
                $resultat = $db->resultAll();   

            foreach($resultat as $row)
            {
           if ($row['nbcmd'] == 0) {            
                 $no_rows = "No sales for that period";
                 $all = '<div>
                    <button class="btn  btn-mini btn-primary bold" type="submit" name="all">All saless</button></div>';
                    }
            }
         }
        }

    // retrieve all sales or sales within period
    if (empty($errors) && empty($no_rows) || isset($_POST['all'])) {

    $search_tot = array(
        "select" => "SELECT COUNT(cmdID) as nbcmd, SUM(`articles_cmd`) as total_articles, SUM(`total_cmd_nofp`) as somme, AVG(`total_cmd_nofp`) as moyenne, MIN(`total_cmd_nofp`) as mini, MAX(`total_cmd_nofp`) as maxi, MIN(`date_cmd`) as date_mini, MAX(`date_cmd`) as date_maxi FROM Commande2",
        "where" => " WHERE ",
        "periode" => "date_cmd BETWEEN '$datedeb' AND '$datefin'"
    );

        if (empty($datebeg) && empty($dateend)) {
           unset($search_tot["where"],$search_tot["periode"]);
        }
    }
    $search_tot = implode(' ', $search_tot);

        // fetch all matching rows
        $db->sql("$search_tot"); 
        $db->execute();
        $resultat = $db->resultAll();   

        foreach($resultat as $row)
        {
            $date1 = date('d-m-Y', strtotime($row['date_mini']));
            $date1 = str_replace('-', '/', $date1);
            $date2 = date('d-m-Y', strtotime($row['date_maxi']));
            $date2 = str_replace('-', '/', $date2);

            $orders= '<div style="text-align: center; font-size: 16px; font-weight: bold;">Sales for '.$date1.' to '.$date2.'/div>';
             ...
        }
...

最佳答案

On some scripts I have like 30 db calls with 30 open/close db using try/catch

但是为什么?您只需要打开一次连接。该连接可用于许多查询,并且可以使用整整八个小时!

只需删除其中一对以外的所有内容。

$connexion = new PDO("mysql:host=$serveur;dbname=$db;charset=$charset",    $login, $pwd);
$connexion -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

最好还是将它移到另一个文件中,该文件包含在需要连接到数据库的每个页面中。这样一来,如果您的数据库设置发生变化,您只需更改一个文件。

on others I have like 30 db calls with 6 open/close db using try/catch.

如果您说的是 30 个查询,这对于单个网页来说是最不寻常的。这是您可能需要重新考虑的事情。重写您的代码以在更少数量的查询中实现相同的目标是可能的。

关于php/pdo/mysql多DB调用最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38483917/

相关文章:

javascript - 通过 jquery 将图像 id 传递给 php mysql 查询

php - Symfony2 - 使用第三方库 (SSRS)

mysql - 如果一行的总和等于 X,则选择行

php - MySQL - 查询列的重复项并返回原始行和重复行

PHP/MySQL 函数导致其他函数停止工作

javascript - 将 JavaScript 数组传递给 PHP 中的输入

php - 如何在不更改扩展名的情况下更改上传文件的名称

MySQL Workbench 6.1 - 导入记录集时出错

php - 使用 PDO MySQL 插入 2 个表

php - 插入和删除不在结果集中的行