使用mysqli包含连接的正确方法

时间:2012-07-15 13:26:08

标签: php mysqli

以下是我在db.php下的代码

    <?php
$con = mysqli_connect('localhost', 'root', '', 'mydb');

/* check connection */
if (!$con) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

?>

在index.php下我将db.php和functions.php包括为:

include("includes/db.php");
include("includes/functions.php");

functions.php也使用db.php连接。我在使用mysql之前没有问题。但在我将mysql更改为mysqli之后,我收到错误“警告:mysqli_query()期望参数1为mysqli,在我的functions.php中给出了null。

这是functions.php下的函数,它有一个错误:

function get_type($r_id){
    $result=mysqli_query($con, "select type from rooms where id=$r_id") or die("select type from rooms where id=$r_id"."<br/><br/>".mysqli_error());
    $row=mysqli_fetch_assoc($result);
    return $row['type'];
}

我的解决方法是在functions.php下的每个函数中添加db.php,它调用mysqli,如:

function get_type($r_id){
    include("includes/db.php");
    $result=mysqli_query($con, "select type from rooms where id=$r_id") or die("select type from rooms where id=$r_id"."<br/><br/>".mysqli_error());
    $row=mysqli_fetch_assoc($result);
    return $row['type'];
}

我想知道这是否是正确的解决方案。

2 个答案:

答案 0 :(得分:3)

问题是您的功能无法使用$ con

您可以为每个函数添加另一个参数

function get_type($con, $r_id)...

然后将$ con传递给它

include('includes/db.php');
include('includes/functions.php');
$blah = get_type($con, 5);

OR

您可以通过添加此global $con;来为每个功能设置$ con,例如

function get_type($r_id){
    global $con;
    $result=mysqli_query($con, "select type from rooms where id=$r_id") or die("select type from rooms where id=$r_id"."<br/><br/>".mysqli_error());
    $row=mysqli_fetch_assoc($result);
    return $row['type'];
}

选择我的朋友......是你的

(可能还有其他方法可以给这只猫留下皮肤)

答案 1 :(得分:0)

在功能中设置$con全局:

function get_type($r_id){
    global $con;
    $result=mysqli_query($con, "select type from rooms where id=$r_id") or die("select type from rooms where id=$r_id"."<br/><br/>".mysqli_error());
    $row=mysqli_fetch_assoc($result);
    return $row['type'];
}
相关问题