我正在尝试编写一些代码来检查用户是否拥有项目列表。项目列表可以是任意长度,但可能不会超过 5 个。
这里涉及到2个表:qrequirements和inventory。
我已经运行了一个循环来检查用户是否拥有每件元素,但我一直在研究如何记录每件元素的所有权结果以及之后如何将其传达给用户。
我可能会以错误的方式处理这一切,也许有更简单的方法,我不知道。
任何帮助都会很棒。到目前为止,这是我的代码:
<?php
// Get the list of required items
$result = mysql_query("select * from qrequirements where qid='2'");
// This might return E.G:
// item1 = '32'
// item2 = '24'
// item3 = '15'
// Loop through each item to check the user has it
while ($row = mysql_fetch_array($result)) {
$itemid = $row["itemid"];
$check_inv = mysql_query("select * from inventory where userid='$userid' AND item = $itemid");
$num_rows = mysql_num_rows($check_inv);
if($num_rows>=1){
// Something in here to confirm the item is owned by the user, while we check the others
}else{
echo "You do not have this item";
}
}
// Notify the user if they have all items required
?>
最佳答案
确定用户需要但没有的项目可以通过单个查询来解决。以下查询应完成该任务。
SELECT * FROM qrequirements t1
WHERE t1.quid = '2'
AND NOT EXISTS ( SELECT 1 FROM inventory t2
WHERE t1.item = t2.item
AND t2.userid = '$userid')
如果您还需要知道用户拥有哪些元素,那么这个类似的查询将完成这项额外的任务。
SELECT * FROM qrequirements t1
WHERE t1.quid = '2'
AND EXISTS ( SELECT 1 FROM inventory t2
WHERE t1.item = t2.item
AND t2.userid = '$userid')
另一个有用的查询是返回所需项目和用户是否拥有该项目的指示器。如果用户没有元素,item_count 将为 0;如果用户有元素,则 item_count 将大于 0。
SELECT t1.*, (SELECT count(*) FROM inventory t2
WHERE t1.item = t2.item
AND t2.userid = '$userid') as item_count
FROM qrequirements t1
WHERE t1.quid = '2'
关于php - 检查选定的项目列表是否在另一个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6345596/