2016-07-23 78 views
1

每次用戶第一次登錄時,我都會保存一些關於它們的信息。如果用戶已經有條目並且條目已過時,那麼它應該被更新。我的問題是試圖比較用戶和數據庫,看他們是否已經有條目。我成功記錄了用戶的詳細信息,但每次用戶登錄時都會這樣做。下面您可以找到我的代碼。將查詢結果與當前用戶進行比較

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

回答

0

您可以通過簡單地使用INSERT ..對重複密鑰更新避免所有這些複雜的邏輯:

$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)" 

你就不需要用戶名綁定和真實姓名PARAMS兩倍的情況。

請注意,這也優於REPLACE INTO,因爲替換的結果是替換整個行而不是僅更新一列。因此,REPLACE INTO可能導致索引必須重新計算。

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` = ? ") 
+0

'$ duplicate',不管信不信,都不會引發任何錯誤。對於如何查看用戶是否已經擁有數據庫條目,我沒有絲毫的線索,但這是我的悲哀嘗試。 @scaisEdge – Nhabbott

+0

蒸汽id是user_id? ..確保你在$ steamprofile ['steamid'] ..eg中有適當的值:使用var_dump($ steamprofile ['steamid']);然後檢查$ duplicate,例如:var_dump($ duplicate); – scaisEdge

相關問題