如何只使用oci_connect()一次然后包含它的文件

时间:2014-05-04 00:10:04

标签: php oracle database-connection connection-string oci

我正在使用PHP和oracle数据库创建一个网站。 我有一个connect.php文件

<?php 
$connect_error = "We are Experiencing Some Technical Difficulty";
oci_connect("asim","asim","localhost/xe") or die($connect_error);
?>

我已将此文件包含在每个页面中!

但每当我必须执行查询时,我必须这样做

function user_exists($username){
    $conn = oci_connect("asim","asim","localhost/xe");

    $username = sanitize($username); 
    $stmt = oci_parse($conn,"SELECT COUNT(username)....");
    oci_execute($stmt); 
    return ($stmt > 0) ? true:false; 
}

我必须在每个函数中包含行$conn = oci_connect("asim","asim","localhost/xe");

有没有办法避免这种情况。

oci_execute Executes a statement previously returned from oci_parse(). oci_parse 需要2个参数,其中一个是connection

1 个答案:

答案 0 :(得分:0)

您需要将第一次调用oci_connect()的结果设置为如此变量:

<?php 
$connect_error = "We are Experiencing Some Technical Difficulty";
$conn = oci_connect("asim","asim","localhost/xe") or die($connect_error);
?>

然后,在您要使用该连接的所有功能中,只需使用global关键字将其引用为global variable

function user_exists($username){
    global $conn;

    $username = sanitize($username); 
    $stmt = oci_parse($conn,"SELECT COUNT(username)....");
    oci_execute($stmt); 
    return ($stmt > 0) ? true:false; 
}