MySQL查询函数内部

时间:2012-12-09 02:35:24

标签: php function mysqli

我有那段代码:

$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

$result = $mysqli->query("SELECT id FROM User");
echo("users: " . $result->num_rows ."<br/>");

function echoUserNum()
{
    $result = $mysqli->query("SELECT id FROM User");
    echo("users: " . $result->num_rows ."<br/>");
}
echoUserNum();

仅打印一次用户数(第一次回显)。问题在哪里?

1 个答案:

答案 0 :(得分:4)

$mysqli超出了函数echoUserNum的范围。尝试全局,或传递连接

function echoUserNum()
{
    global $mysqli;
    $result = $mysqli->query("SELECT id FROM User");
    echo("users: " . $result->num_rows ."<br/>");
}

function echoUserNum($mysqli)
{
    $result = $mysqli->query("SELECT id FROM User");
    echo("users: " . $result->num_rows ."<br/>");
}
echoUserNum($mysqli);