mysqli_query给出null结果php

时间:2014-05-09 14:18:35

标签: php mysql

我正在尝试查询数据库,但mysqli_query($ dbc,$ query)始终返回{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null} 我的代码中没有任何var_dump。

$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

if (mysqli_connect_errno()){
    trigger_error ('Could not connect to MySql: ' . mysqli_connect_error());
    echo "it had an error";
} else {
    mysqli_set_charset($dbc, 'utf8');
    echo "it connected";
}

这回应“它连接”

function getGames($dbc){           
    $query="SELECT * FROM games WHERE min_players <= ".$number." AND max_players >=".$number.";";         
    $result = mysqli_query($dbc, $query) or trigger_error("Query: $query\ n<br />MySQL Error: " . mysqli_error($dbc));

    if(mysqli_affected_rows($dbc)) {
        return $result;
    } else {
        return "no affected rows";
    }
}

当我在phpMyAdmin中运行查询时,我得到了几行结果。

此外,该函数在调用时不会返回“没有受影响的行”:

$result = getGames($dbc);
echo json_encode($result);

2 个答案:

答案 0 :(得分:1)

除非您在全球范围内声明$number,否则it won't be available in the scope of getGames。你应该把它传递给:

function getGames($dbc, $number) {
    // ...

此外,您可以输出正在运行的确切SQL,以便您可以在phpMyAdmin中测试它(因此您可以验证$number是否正确传递给您的函数):

echo $query;

最后,mysqli_affected_rows不会返回SELECT语句中的行数。请改为mysqli_num_rows

$sql = sprintf('Your SELECT statement with %d number', $number);
echo $sql; // To visually verify the SQL is valid

$query = mysqli_query($dbc, $sql);

if (false !== $query) {
    return mysqli_num_rows($query);
} else {
    return mysqli_error($dbc);
}

答案 1 :(得分:0)

我刚刚将你的mysqli_affected_rows($ dbc)更改为mysqli_num_rows($ result),并且适合我。 mysqli_affected_rows($ dbc)返回受上一次INSERT,UPDATE,REPLACE或DELETE查询影响的行数。

function getGames($ dbc){
    $ query =“SELECT * FROM games WHERE min_players&lt; =”。$ number。“AND max_players&gt; =”。$ number。“;”;

    $ result = mysqli_query($ dbc,$ query)或trigger_error(“Query:$ query \ n
MySQL Error:”。mysqli_error($ dbc));

if(mysqli_num_rows($result)) {
    return $result;
} else {
    return "no affected rows";
}

}