学习PHP PDO ..想知道在涉及多个查询时使用它的正确方法

时间:2022-08-15 15:20:11

In the past I would just create a class to connect to a database, and then run a bunch of methods to run queries.. like so:

在过去,我只想创建一个连接数据库的类,然后运行一堆方法来运行查询..就像这样:

class connectDB
{
public $db_host = "asdf.db.asdf.hostedresource.com";
public $db_name = "asdf";
public $db_user = "asdf";
public $db_pass = "asdf!1";
public $result;

function setDB_Host($value){
 $this->db_host=$value;
}

function setDB_name($value){
 $this->db_name=$value;
}

 function setDB_user($value){
 $this->db_user=$value;
}

function setDB_pass($value){
 $this->db_pass=$value;
}

function makeConnection()
{
    $connection = mysql_connect($this->db_host, $this->db_user, $this->db_pass) or die
    ("Unable to connect!");
    mysql_select_db($this->db_name) or die(mysql_error());
}

function setQuery($query)
{
    $this->result = mysql_query($query) or die(mysql_error());
}


    class video
    {
       public $sequence;
       public $fileName;
       public $vidTitle;
       public $vidCat;
       public $thumbName;


function addVideo($sequence, $fileName, $vidTitle, $vidCat, $thumbName)
{
    $this->connect-> setQuery("SELECT COUNT(id) AS numrows FROM vids WHERE vidCat = '$vidCat'");
    $row = mysql_fetch_array($this->connect->result);
    $sequence = $row['numrows'] + 1;
    $this->connect->setQuery("INSERT INTO vids (sequence, fileName, vidTitle, vidCat, thumbName) VALUES ('$sequence', '$fileName', '$vidTitle', '$vidCat', '$thumbName') ");

}

    function addKeypoints($keypoints, $mins, $secs)
{
        $v_id = mysql_insert_id();

    for ($i=0; $i<sizeof($keypoints); $i++)
    {       
        $totalsecs = ($mins[$i]*60) + $secs[$i];
        $this->connect->setQuery("INSERT INTO keypoints (v_id, totalsecs, keypoints, mins, secs) VALUES ('$v_id', '$totalsecs', '$keypoints[$i]', '$mins[$i]', '$secs[$i]') ");
    }

}

without wanting to read all that. Basically I just run a bunch of methods that access my first class, and run queries. I don't understand how this would work in a PDO context. PDO should be making this sort of thing easier since it's OOP based.. correct?

不想读所有这些。基本上我只是运行一堆访问我的第一个类的方法,并运行查询。我不明白这在PDO环境中是如何工作的。 PDO应该让这种事情变得更容易,因为它是基于OOP的......对吗?

    $hostname = "aaa.db.7149468.aaa.com";
    $username = "coolcaaaaodez";
    $password = "aaaa";

    try
    {
$dbh = new PDO("mysql:host=$hostname;dbname=coolcodez", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $dbh->prepare("INSERT INTO links (link, cool, difficulty) values (:link, :cool, :difficulty)");

$stmt->bindParam(':link',       $_POST['link']);
$stmt->bindParam(':cool',       $_POST['cool']);
$stmt->bindParam(':difficulty', $_POST['difficulty']);

if(isset($_POST['submit-links']))
{
    $stmt->execute();
    echo "row added <br />";
}
    }
   catch(PDOException $e)
   {
        echo $e->getMessage();
   }

basically what i'm asking is.. the try / catch thing really trips me up. Does just the connection itself need to be put into a try / catch block, and then I could prepare queries within each of my methods belonging to a class? Or does each sequence of events (database connection, query, results, etc) need to be stuck within a try / catch block. PDO is a little fancy for my needs, but I'm trying to learn, and I'd like to know the best general way to write it when a large number of queries are involved.

基本上我要问的是..尝试/捕捉的东西真的让我感到惊讶。是否只需要将连接本身放入try / catch块中,然后我可以在属于某个类的每个方法中准备查询?或者每个事件序列(数据库连接,查询,结果等)是否需要卡在try / catch块中。 PDO对我的需求有点花哨,但我正在努力学习,并且我想知道在涉及大量查询时编写它的最佳通用方法。

2 个解决方案

#1


1  

PDO should be making this sort of thing easier since it's OOP based.. correct?

PDO应该让这种事情变得更容易,因为它是基于OOP的......对吗?

Yes... in a way. Being fine instrument, OOP requires some skill in using - only then it will make things easier indeed. Otherwise, it will make things quite harder.

是的......在某种程度上。作为优秀的乐器,OOP需要一些使用技巧 - 只有这样才能使事情更容易。否则,它将使事情变得更加艰难。

All the code you need, actually, is

实际上,您需要的所有代码都是

if(isset($_POST['submit-links']))
{
    require 'pdo.php';
    $sql  = "INSERT INTO links (link, cool, difficulty) values (?, ?, ?)";
    $data = array($_POST['link'], $_POST['cool'], $_POST['difficulty']);
    $dbh->prepare($sql)->execute($data);
}

The rest of your code is superfluous for two reasons:

您的其余代码是多余的,原因有两个:

  1. surely DB connection code should be stored in a separate file and included in all other files, instead of being duplicated each time. A good example for the connection code can be found in the PDO tag wiki
  2. 当然,数据库连接代码应该存储在一个单独的文件中,并包含在所有其他文件中,而不是每次都重复。可以在PDO标记wiki中找到连接代码的一个很好的示例

  3. This try-catch stuff, which indeed confuse many inexperienced developers. In fact, you don't need it here at all - or, at least, not in this form. Just because PHP can handle the error itself (and do it better than average PHP user, to be honest). So, you can just omit this try/catch stuff. Further reading: The (im)proper use of try..catch.
  4. 这种尝试捕获的东西,确实让许多缺乏经验的开发人员感到困惑。事实上,你根本不需要它 - 或者至少不是这种形式。仅仅因为PHP本身可以处理错误(并且比普通的PHP用户做得更好,说实话)。所以,你可以省略这个try / catch的东西。进一步阅读:(im)正确使用try..catch。

#2


0  

Think about it this way - for any error that PDO might encounter, it will throw an exception. WHen using the mysql_ functions, they either just return FALSE/NULL or give you a notice, a warning or even a fatal error. With PDO, you do not get errors, you get exceptions. So you can catch something that mysql_ would have caused to stop the script all together.

这样考虑一下 - 对于PDO可能遇到的任何错误,它都会抛出异常。当使用mysql_函数时,它们只返回FALSE / NULL或者给你一个通知,一个警告甚至一个致命的错误。使用PDO,您不会收到错误,您会遇到异常。因此,您可以捕获mysql_会导致脚本全部停止的内容。

So in the end, you probably want to have a try/catch block around every call that could result in some kind of error, and you know how to handle it. If that disturbs your eye, you can write a short class extending PDO that would do the try/catch logic inside and return you either the results or FALSE/NULL as would mysql_ functions do.

所以最后,您可能希望在每次调用时都有一个try / catch块,这可能会导致某种错误,并且您知道如何处理它。如果这扰乱了你的眼睛,你可以编写一个扩展PDO的短类,它会在里面执行try / catch逻辑,并返回结果或者像mysql_函数那样返回FALSE / NULL。

#1


1  

PDO should be making this sort of thing easier since it's OOP based.. correct?

PDO应该让这种事情变得更容易,因为它是基于OOP的......对吗?

Yes... in a way. Being fine instrument, OOP requires some skill in using - only then it will make things easier indeed. Otherwise, it will make things quite harder.

是的......在某种程度上。作为优秀的乐器,OOP需要一些使用技巧 - 只有这样才能使事情更容易。否则,它将使事情变得更加艰难。

All the code you need, actually, is

实际上,您需要的所有代码都是

if(isset($_POST['submit-links']))
{
    require 'pdo.php';
    $sql  = "INSERT INTO links (link, cool, difficulty) values (?, ?, ?)";
    $data = array($_POST['link'], $_POST['cool'], $_POST['difficulty']);
    $dbh->prepare($sql)->execute($data);
}

The rest of your code is superfluous for two reasons:

您的其余代码是多余的,原因有两个:

  1. surely DB connection code should be stored in a separate file and included in all other files, instead of being duplicated each time. A good example for the connection code can be found in the PDO tag wiki
  2. 当然,数据库连接代码应该存储在一个单独的文件中,并包含在所有其他文件中,而不是每次都重复。可以在PDO标记wiki中找到连接代码的一个很好的示例

  3. This try-catch stuff, which indeed confuse many inexperienced developers. In fact, you don't need it here at all - or, at least, not in this form. Just because PHP can handle the error itself (and do it better than average PHP user, to be honest). So, you can just omit this try/catch stuff. Further reading: The (im)proper use of try..catch.
  4. 这种尝试捕获的东西,确实让许多缺乏经验的开发人员感到困惑。事实上,你根本不需要它 - 或者至少不是这种形式。仅仅因为PHP本身可以处理错误(并且比普通的PHP用户做得更好,说实话)。所以,你可以省略这个try / catch的东西。进一步阅读:(im)正确使用try..catch。

#2


0  

Think about it this way - for any error that PDO might encounter, it will throw an exception. WHen using the mysql_ functions, they either just return FALSE/NULL or give you a notice, a warning or even a fatal error. With PDO, you do not get errors, you get exceptions. So you can catch something that mysql_ would have caused to stop the script all together.

这样考虑一下 - 对于PDO可能遇到的任何错误,它都会抛出异常。当使用mysql_函数时,它们只返回FALSE / NULL或者给你一个通知,一个警告甚至一个致命的错误。使用PDO,您不会收到错误,您会遇到异常。因此,您可以捕获mysql_会导致脚本全部停止的内容。

So in the end, you probably want to have a try/catch block around every call that could result in some kind of error, and you know how to handle it. If that disturbs your eye, you can write a short class extending PDO that would do the try/catch logic inside and return you either the results or FALSE/NULL as would mysql_ functions do.

所以最后,您可能希望在每次调用时都有一个try / catch块,这可能会导致某种错误,并且您知道如何处理它。如果这扰乱了你的眼睛,你可以编写一个扩展PDO的短类,它会在里面执行try / catch逻辑,并返回结果或者像mysql_函数那样返回FALSE / NULL。