要检查的PHP脚本如果用户已存在于MySQL数据库中

时间:2013-12-12 08:56:55

标签: php mysql database facebook post

我正在为Facebook创建简单的游戏。使用app的所有用户都被写入数据库。我需要经常检查如果用户已经存在在数据库中,该怎么做呢?

所以我有变量$name = $user_profile['name'];它成功返回用户名

这是我检查用户是否已存在于数据库中的代码部分。

$user_profile = $facebook->api('/me');
$name = $user_profile['name'];

      $mysqli = new mysqli("host","asd","pw","asdf");
                   echo "1";
               $sql = "SELECT COUNT(*) AS num FROM myTable WHERE userName = ?";
                   echo "2";
                if ($stmt = $mysqli->prepare($sql)) {
                   echo "3";
                $stmt->bind_param('s', $name);
                   echo "4";
                $stmt->execute();
                   echo "5";
                $results = $stmt->get_result();
                   echo "6";
                $data = mysqli_fetch_assoc($results);
                   echo "7";
                }
           if($data['num'] != 0)
            {
                    echo "bad";
                    print "user already exists\n";
            } else {
                    echo "good";    
                    $apiResponse = $facebook->api('/me/feed', 'POST', $post_data);
                    print "No user in database\n";
            }
    }

此代码无效,应在用户墙上发布数据如果用户不在数据库中。我花了很多时间找到原因,但没有成功。调试后它没有显示任何错误。要在我使用echo "number"的每一行之后找到哪行不正确,现在我知道哪一行不正确。它会打印1 2 3 4 5并卡住。 (代码未加载的所有内容。)这意味着此行$results = $stmt->get_result();不正确。但我误解了这条线有什么问题?

如果我对所有代码加载进行注释(然后在用户的墙上打印1 2 3 4 5 6 7 No user in database!和它post data。)但在这种情况下,程序总是这样做,而不是检查数据库。

此外,我尝试将COUNT(*)更改为COUNT(userName),但也是如此。

那你能帮助我吗?

我读过这个:Best way to check for existing user in mySQL database?但它没有帮助我。

P.S。在这种情况下,我需要使用FB用户名。

1 个答案:

答案 0 :(得分:0)

您可以试试这个,$stmt->fetch()而不是mysqli_fetch_assoc($results)

    $mysqli = new mysqli("host","asd","pw","asdf");
echo "1";
/* Create the prepared statement */
$stmt = $mysqli->prepare("SELECT COUNT(*) AS num FROM myTable WHERE userName = ?") or die("Prepared Statement Error: %s\n". $mysqli->error);
    /* Execute the prepared Statement */
    $stmt->execute();

    /* Bind results to variables */
    $stmt->bind_result($name);

    $data = $stmt->fetch();
    if($data['num'] > 0)
    {
        echo "bad";
        print "user already exists\n";
    } else {
        echo "good";
        $apiResponse = $facebook->api('/me/feed', 'POST', $post_data);
        print "No user in database\n";
    }   

    /* Close the statement */
    $stmt->close();

参考:http://forum.codecall.net/topic/44392-php-5-mysqli-prepared-statements/