Re: question about best practice for coding sql statements

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 11-11-12 06:30 AM, tamouse mailing lists wrote:
I'm curious how others feel about this. When I'm creating an SQL
string, either for a non-prepared or prepared execution, I build it in
a variable and then pass the variable to the query or prepare
function. This lets me easily add something to view the SQL statement,
and also if there's an error, emit the SQL statement. Thus:

$sql = "SELECT * FROM TABLE WHERE id=$id";
if ($debug) error_log($sql." from ".__FILE__.' at '.__LINE__' in
'__FUNCTION__.PHP_EOL); // just an example
$rslt = $db->query($sql) or die("Could not get result from $sql:
".$db->errno.": ".$db->error.".".PHP_EOL);

and so on...
While I am not a big fan of OOP, I do like PDO, and recommend its use.

This is a sample function I have to maintain a record based on POSTed changes:

function updatecategory($dbh, $x) {

 $sql = "UPDATE gallery_category
          SET category_name = :name,
              category_description = :description
          WHERE category_id = :id";

  $catname = fieldcheck($x['catname']);
  $catdescription = textfieldcheck($x['catdescription']);

  $stmt = $dbh->prepare($sql);

  try {
    $stmt->bindParam(':name', $catname);
    $stmt->bindParam(':description', $catdescription);
    $stmt->bindParam(':id', $x['cid']);
    $stmt->execute();
  } catch (PDOException $e) {
    return 'Error updating category orders: ' . $e->getMessage();
  }

return "Maintained category " . $catname;

}

PDO is very efficient when you are looping through updates, and the error handling is simple to code.

Using a disciplined format keeps everything readable and easy to use as a template for additional work.

Cheers
Stephen

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux