note 79584 added to function.ociparse
| From: | michael dot virnstein at brodos dot de | Date: | Tue, 04 Dec 2007 16:43:32 +0000 |
| Subject: | note 79584 added to function.ociparse | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-132802@lists.php.net to get a copy of this message | ||
A neat way to parse a query only once per script, if the query is done inside a function:
<?php
function querySomething($conn, $id)
{
static $stmt;
if (is_null($stmt)) {
$stmt = oci_parse($conn, 'select * from t where pk = :id');
}
oci_bind_by_name($stmt, ':id', $id, -1);
oci_execute($stmt, OCI_DEFAULT);
return oci_fetch_array($stmt, OCI_ASSOC);
}
?>
With the static variable, the statment handle isn't closed after the function has terminated.
Very nice for functions that are called e.g. in loops. Unfortunately this only works for static sql.
If you have dynamic sql, you can do the following:
<?php
function querySomething($conn, $data)
{
static $stmt = array();
$first = true;
$query = 'select * from t';
foreach ($data as $key => $value) {
if ($first) {
$first = false;
$query .= ' where ';
} else {
$query .= ' and ';
}
$query .= "$key = :b$key";
}
$queryhash = md5($query);
if (is_null($stmt[$queryhash])) {
$stmt[$queryhash] = oci_parse($conn, $query);
}
foreach ($data as $key => $value) {
// don't use $value, because we bind memory addresses here.
// this would result in every bind pointing at the same value after foreach
oci_bind_by_name($stmt[$queryhash], ":b$key", $data[$key], -1);
}
oci_execute($stmt[$queryhash], OCI_DEFAULT);
return oci_fetch_array($stmt[$queryhash], OCI_ASSOC);
}
?>
----
Server IP: 217.13.201.10
Probable Submitter: 194.153.150.17
----
Manual Page -- http://www.php.net/manual/en/function.ociparse.php
Edit -- https://master.php.net/note/edit/79584
Del: integrated -- https://master.php.net/note/delete/79584/integrated
Del: useless -- https://master.php.net/note/delete/79584/useless
Del: bad code -- https://master.php.net/note/delete/79584/bad+code
Del: spam -- https://master.php.net/note/delete/79584/spam
Del: non-english -- https://master.php.net/note/delete/79584/non-english
Del: in docs -- https://master.php.net/note/delete/79584/in+docs
Del: other reasons-- https://master.php.net/note/delete/79584
Reject -- https://master.php.net/note/reject/79584
Search -- https://master.php.net/manage/user-notes.php