将查询结果与当前用户

时间:2016-07-23 07:36:26

标签: php mysql

每次用户首次登录时,我都会保存一些有关它们的信息。如果用户已经输入并且条目已过时,则应更新该条目。我的问题是尝试将用户与数据库进行比较,看看他们是否已经有了一个条目。我成功记录了用户的详细信息,但每次用户登录时都会这样做。您可以在下面找到我的代码。

$conn = new mysqli('host', 'user', 'password', 'db');
if ($conn->connect_error) {
    die("Error; Contact Support!");
}

$stmt = $conn->prepare("select * from users where steamid=? ");
$stmt->bind_param('s', $steamprofile['steamid']);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($res);
$duplicate = mysqli_num_rows($res);
if ($duplicate == 0) {
    $stmt1 = $conn->prepare("REPLACE INTO `users` SET `steamid` = ?,`realname` = ?,`username` = ?");
    $stmt1->bind_param('sss', $steamprofile['steamid'], $steamprofile['realname'], $steamprofile['personaname']);
    $stmt1->execute();
    $stmt1->store_result();
    $stmt1->bind_result($res1);
    if ($res1 === TRUE) {
        echo "";
    }
    $stmt1->close();
    $stmt->close();
    mysqli_close($conn);
}

2 个答案:

答案 0 :(得分:0)

你可能有拼写错误

duplicate = mysqli_num_rows($res);

而不是

$duplicate = mysqli_num_rows($res);

(但这不应该引起错误?)

您使用

("REPLACE INTO `users` SET `steamid` = ?,`realname` = ?,`username` = ?")

我认为你应该为新用户使用INSERT并为现有用户更新

("INSERT INTO `users` (`steamid`,`realname`, `username`) values( ?, ?,?")

("UPDATE `users` SET `steamid` = ?,`realname` = ?,`username` = ?
  WHERE `your_user_id`  = ? ")

答案 1 :(得分:0)

只需使用INSERT就可以避免所有这些复杂的逻辑.. ON DUPLICATE KEY UPDATE:

$conn = new mysqli('host', 'user', 'password', 'db');
if ($conn->connect_error) {
    die("Error; Contact Support!");
}

$query = "INSERT INTO `users` SET `steamid` = ?,`realname` = ?,`username` = ? ON DUPLICATE KEY UPDATE realname=? , username=?"
$stmt1 = $conn->prepare($query);
$stmt1->bind_param('sssss', $steamprofile['steamid'], 
        $steamprofile['realname'], $steamprofile['personaname'], 
        $steamprofile['realname'], $steamprofile['personaname']);
$stmt1->execute();
$stmt1->store_result();
$stmt1->bind_result($res1);
if ($res1 === TRUE) {
    echo "";
}
$stmt1->close();
mysqli_close($conn);

您完全不需要首先运行查询以查明记录是否已存在。

另请注意,查询也可以写为

$query = "INSERT INTO `users` SET `steamid` = ?,`realname` = ?,`username` = ? ON DUPLICATE KEY UPDATE realname=VALUES(realname) , username=VALUES(username)"

在这种情况下,您不需要两次绑定用户名和realname参数。

请注意,这也优于REPLACE INTO,因为replace会导致整个行被替换而不是只更新一列。因此,REPLACE INTO可能导致必须重新计算索引。