gpt4 book ai didi

php - PHP脚本。检查用户是否已经在MySQL数据库中

转载 作者:行者123 更新时间:2023-11-30 00:56:19 28 4
gpt4 key购买 nike

我正在为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();不正确,因为在它之后不打印值。这里有什么问题?

最佳答案

这个查询很简单:

SELECT
COUNT(*)
FROM
myTable
WHERE
userName = :user_name


如果结果不为0,则该用户存在。

PHP中的mysqli实现

$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";
}
}

关于php - PHP脚本。检查用户是否已经在MySQL数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20522340/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com