为什么我的count()在空的时候返回1?

时间:2014-09-16 10:22:42

标签: php mysql mysqli phpmyadmin

尝试从数据库返回信息(空白)。它继续返回值1但是它应该是0.数据库是空的但是返回"我存在"。

       <?php

set_time_limit(0);

$db = new mysqli("localhost","wwwrhino_Twitch","","wwwrhino_Twitch");

if($db->connect_errno) {
    echo $db->connect_error;
    die('Sorry, We are having some problems');
}


$offset = 0;
$count = 1;

do {
    $Brad = json_decode(file_get_contents(
        'https://api.twitch.tv/kraken/channels/greatbritishbg/follows?limit=25&offset='  . $offset
    )); 
    $Darren = json_decode(file_get_contents(
        'https://api.twitch.tv/kraken/channels/Skairpigg/follows?limit=25&offset='  . $offset
    )); 



    foreach($Brad->follows as $Bradfollow) {
        $username = (string)$Bradfollow->user->name;
    //$result = $db->query("SELECT count(Username) FROM `Users` WHERE `Username` ='$username' ");
    $result = $db->query("SELECT count(Username) AS total_users FROM `Users` WHERE `Username` ='$username' ");
    if ($result->total_users > 0) {
        echo 'I Exist!: '. (int)$result . ": " . $username . "<br>";     
        var_dump($result);
    }
    else { 
        echo 'Add me'; 
        echo "<p>Inserting Value:". $username ."</p>";
        echo "Var Dump:" . var_dump($result);
            if($insert = $db->query("
        INSERT INTO Users (Username, Minecraft_Name) 
        VALUES ('$username', 'Garrett')
        ")) {
        echo $db->affected_rows . "<br>";
        }
    }
    $offset+=25;
} while (!empty($Brad->follows));
?>

这是我的数据库:

enter image description here

任何人都可以解释为什么结果会不断返回为&#34; 1&#34;

由于

2 个答案:

答案 0 :(得分:1)

你正在使用mysqli,正确的方法是 -

$res = $mysqli->query("SELECT id FROM test ORDER BY id ASC");

echo "Reverse order...\n";
for ($row_no = $res->num_rows - 1; $row_no >= 0; $row_no--) {
    $res->data_seek($row_no);
    $row = $res->fetch_assoc();
    echo " id = " . $row['id'] . "\n";
}

参考 - phpmanual

尝试 -

$result = $db->query("SELECT count(Username) AS total_users FROM `Users` WHERE `Username` ='$username' ");
$row = $result->fetch_assoc();

并确保您可以尝试dump $row并查看其返回的内容。然后检查index -

if ($row['total_users'] > 0) {
    //your code
}

您只执行始终返回true1的查询。你还必须从资源中获取数据。

答案 1 :(得分:0)

这样做:

$result = $db->query("SELECT count(Username) as cnt FROM `Users` WHERE `Username` ='$username' ");
$row = $result->result();
if ($row->cnt > 0) {
    echo 'I Exist!: '. (int)$result . ": " . $username . "<br>"; 
 }

Reference