你好,我有一个简单的SQL SELECT和INSERT,这个网站帮助了我,但现在我需要这样做,以便它只对不存在的行进行插入。
因此,如果该行在那里,请跳到下一行。我有它,所以当用户达到 100 场战斗时,它会给他们一个奖励,但当然,如果它继续插入,他们将有 100 个奖励来完成同样的 100 场战斗。所以需要一些如何检查用户是否得到了奖励,然后如果没有给他们呢?
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM users where wins >= 100")
or die(mysql_error());
$reward = '100 battles won' ;
$rewardimage = 'chnage after' ;
echo "<table border='1'>";
echo "<tr> <th>username</th> <th>wins</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
mysql_query("INSERT INTO User_Rewards
(username, reward_name, reward_image) VALUES('".$row['username']."', '".$reward."', '".$rewardimage."' ) ")
or die(mysql_error());
}
我该怎么做呢?因为目前它只是继续做插入但需要它,所以如果用户有奖励,那么不要为该用户做插入。奖励存储在$reward的一侧。
您正在寻找的是与插入相结合UNIQUE KEY
...在重复键更新时。
另外,请停止使用古老的mysql_*
函数编写新代码。它们不再维护,社区已开始弃用过程。相反,您应该了解预准备语句并使用PDO或MySQLi。如果您无法决定,本文将帮助您选择。如果你想学习,这里有一个非常好的PDO相关教程。
while($row = mysql_fetch_array( $result )) {
if(mysql_num_rows(mysql_query("select * from User_Resards where username='".$row['username']."' ")) == 0) {
mysql_query("INSERT INTO User_Rewards (username, reward_name, reward_image) VALUES('".$row['username']."', '".$reward."', '".$rewardimage."' ) ") or die(mysql_error());
}
}
你可以试试这个。