当我使用该函数运行查询时,mysqli查询的问题

时间:2014-06-18 21:22:18

标签: php mysqli

为什么在函数中使用mysqli运行查询时会出现此错误?它在功能之外工作正常。在运行该函数时,错误表明" $ db"变量未定义。

<?php

$username = 'username';
$password = 'password';

$db = new mysqli('localhost', 'root', 'root', 'rocketforce_blog');



    $result = $db->query("SELECT * FROM users WHERE user_name = '$username' AND password = '$password'");
    $row = $result->num_rows;
    $cnt = count($row);
    echo $cnt;

//=======================================================================================

    function user_exists($username, $password)
    {
        $result = $db->query("SELECT * FROM users WHERE user_name = '$username' AND password = '$password'");
        $row = $result->num_rows;
        $cnt = count($row);
        return $cnt;
    }

    echo user_exists($username, $password);

?>

1 个答案:

答案 0 :(得分:1)

The variable $db is not known in the scope of this function。如果要在此函数中知道它,则必须将$ db作为参数传递给函数。例如

function user_exists($db, $username, $password)
{
   $result = $db->query("SELECT * FROM users WHERE user_name = '$username' AND password = '$password'");
    $row = $result->num_rows;
    $cnt = count($row);
    return $cnt;
}

echo user_exists($db, $username, $password);

或者将全局$ db变量导入函数的范围。像那样:

function user_exists($username, $password)
{
   global $db;
   $result = $db->query("SELECT * FROM users WHERE user_name = '$username' AND password = '$password'");
    $row = $result->num_rows;
    $cnt = count($row);
    return $cnt;
}

echo user_exists($username, $password);

第一个是更好的一个,因为你可以使用类型提示,传递不同的连接等等......