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) {
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);
}
?>