我正在为Facebook创建应用程序,所有使用应用程序的用户都被写入数据库。所以我需要经常检查如果用户已经在数据库中,如何正确地做到这一点?
所以我有变量$name = $user_profile['name'];
它得到用户的名字
这是我将用户插入数据库的功能。
$mysqli = new mysqli("asd","asd","pw","asd");
if ($stmt = $mysqli->prepare("INSERT into myTable (score, userName) VALUE (?,?) ")) {
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
} else {
}
$stmt->bind_param('ss', $score, $name);
$stmt->execute();
if ($stmt->error != '') {
echo ' error:'.$stmt->error;
} else {
echo 'success';
}
$stmt->close();
} else {
echo 'error:'.$mysqli->error;
}
$mysqli->close();
现在我需要If
函数来检查用户是否已经在数据库中。据我了解它应该类似于插入到数据库,而只是INSERT into
我需要使用SELECT from
如何成功地做到这一点?谢谢。
我读过这个:Best way to check for existing user in mySQL database?但它不会帮助我。
更新
现在我的代码如下:
$mysqli = new mysqli("host","asd","pw","asdf");
echo "1";
$sql = "SELECT COUNT(*) AS num FROM myTable WHERE userName = ?";
echo "2";
if ($stmt = $mysqli->prepare("SELECT COUNT(*) AS num FROM under WHERE userName = ? ")) {
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";
}
它打印1 2 3 4 5.这意味着此行$results = $stmt->get_result();
不正确,因为它没有打印值。这可能有什么问题?
答案 0 :(得分:0)
此查询很简单:
SELECT
COUNT(*)
FROM
myTable
WHERE
userName = :user_name
如果结果不为0,则表示用户存在。
$sql = "SELECT
COUNT(*) AS num
FROM
myTable
WHERE
userName = ?";
if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param('s', $name);
$stmt->execute();
$results = $stmt->get_result();
$data = mysqli_fetch_assoc($results);
if($data['num'] != 0)
{
print "user already exists\n";
}
}
答案 1 :(得分:0)
1)如果你写FB用户数据,你不应该检查NAME!您应该检查 FB用户ID - 它始终是唯一的,名称可以是相同的。
2)永远不要COUNT(*)
- 改为使用COUNT(id)