Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.php > #5512

Re: Clean PDO-MySQL Statement

From "M. Strobel" <sorry_no_mail_here@nowhere.dee>
Newsgroups comp.lang.php
Subject Re: Clean PDO-MySQL Statement
Date 2012-04-13 14:42 +0200
Message-ID <9uql9iFoj0U1@mid.uni-berlin.de> (permalink)
References <9uqh35FovkU1@mid.individual.net>

Show all headers | View raw


Am 13.04.2012 13:30, schrieb Alexandra Herzog:
> Hi everyone,
> 
> I am using the PDO with MySQL for the first time and created a statement. Besides from individual input validation (which I always do), I would like to know, if you consider the following to be a clean statement:
> 
> That's what I figured from googled examples:
> 
> include ("pdoconnect.php");
> $stmt = $dbh->prepare("SELECT firstname, name FROM telephonebook WHERE from_work = :workstatus ORDER BY :mywish ASC");

prepare will give you bool(false) if something is wrong. If you do not test for this
your $stmt->bindParam() can fail. Either always test it, wrap the call, or use
exception mode (see below).


> $stmt->bindParam(':workstatus', $n, PDO::PARAM_INT);
> $stmt->bindParam(':mywish', $value, PDO::PARAM_STR);
> $n = 1; $order = "firstname";
> $stmt->execute();
> 
> echo "<u>".$stmt->rowCount()."</u>\r\n";
> while ($row = $stmt->fetch())
>   echo $row['firstname']."&nbsp;".$row['name']."<br>";
> $stmt->closeCursor();
> $dbh = null;
> 
> 
> in pdoconnect.php:
> -----------------------
> try
>   { $dbh = new PDO('mysql:host=host1.myhost.com;dbname=mydb1', alex, mypass);

Those making use of the OO goodies would define their own wrapper class where they
put all the db helpers, like this:

class Dbman extends PDO {
    function __construct($dburl) {
        parent::__construct($dburl);
        # $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
        # $this->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION );
    }
}

Errormode exception tells PDO to thow an exception on errors. This makes it easy to
frame your code with try - catch without testing every single database request.

A lot more can be said to this subject...

/Str.

Back to comp.lang.php | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Clean PDO-MySQL Statement Alexandra Herzog <herzog.alex@arcor.de> - 2012-04-13 13:30 +0200
  Re: Clean PDO-MySQL Statement "M. Strobel" <sorry_no_mail_here@nowhere.dee> - 2012-04-13 14:42 +0200
  Re: Clean PDO-MySQL Statement Jerry Stuckle <jstucklex@attglobal.net> - 2012-04-13 12:07 -0400

csiph-web