note 100850 modified in pdo.exec by danbrown
| From: | danbrown@php.net | Date: | Thu, 11 Nov 2010 02:49:43 +0000 |
| Subject: | note 100850 modified in pdo.exec by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-173933@lists.php.net to get a copy of this message | ||
For those that want an exec that handles params like prepare/execute does. You can simulate this
with another function
<?php
class Real_PDO extends PDO {
public function execParams($sql, $params) {
$stm = $this->prepare($sql);
$result = false;
if( $stm && $stm->execute($params) ) {
$result = $stm->rowCount();
while( $stm->fetch(PDO::FETCH_ASSOC) ) {
}
}
return $result;
}
}
?>
Remember though, if you are doing a lot of inserts, you'll want to do it the manual way, as the
prepare statement will speed up when doing multiple executes(inserts). I use this so I can place
all my SQL statements in one place, and have auto safe quoting against sql-injections.
If you are wondering about the fetch after, remember some databases can return data SELECT-like data
from REMOVE/INSERTS. In the case of PostgreSQL, you can have it return you all records that were
actually removed, or have the insert return the records after the insert/post field functions, and
io trigger fire, to give you normalized data.
<?php
define("BLAH_INSERT", "INSERT INTO blah (id,data) VALUES(?,?)");
$pdo = new Real_PDO("connect string");
$data = array("1", "2");
$pdo->execParams(BLAH_INSERT, $data);
?>
--was--
For those that want an exec that handles params like prepare/execute does. You can simulate this
with another function
class Real_PDO extends PDO {
public function execParams($sql, $params) {
$stm = $this->prepare($sql);
$result = false;
if( $stm && $stm->execute($params) ) {
$result = $stm->rowCount();
while( $stm->fetch(PDO::FETCH_ASSOC) ) {
}
}
return $result;
}
}
Remember though, if you are doing a lot of inserts, you'll want to do it the manual way, as the
prepare statement will speed up when doing multiple executes(inserts). I use this so I can place
all my SQL statements in one place, and have auto safe quoting against sql-injections.
If you are wondering about the fetch after, remember some databases can return data SELECT-like data
from REMOVE/INSERTS. In the case of PostgreSQL, you can have it return you all records that were
actually removed, or have the insert return the records after the insert/post field functions, and
io trigger fire, to give you normalized data.
define("BLAH_INSERT", "INSERT INTO blah (id,data) VALUES(?,?)");
$pdo = new Real_PDO("connect string");
$data = array("1", "2");
$pdo->execParams(BLAH_INSERT, $data);
http://php.net/manual/en/pdo.exec.php