开发者

Learning PHP PDO.. would like to know the correct way to use it when many queries are involved

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?

    $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.


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

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.

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. 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.


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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜