简体   繁体   English

通过第一列 id 检查第二列

[英]check through second column by first column id

I have 2 columns under sales table in SQL as below我在 SQL 的销售表下有 2 列,如下所示

id ID itemid项目编号
1 1 31 31
1 1 32 32
1 1 33 33
1 1 34 34

I need through the PHP to check by the id, if the $_SESSION['id'] has any item number in the second column then tell the user that the item already exists, otherwise add this item to DB.. I did do fat the below code but it doesn't work, it will print both conditions if statement我需要通过 PHP 来检查 id,如果 $_SESSION['id'] 在第二列中有任何项目编号,然后告诉用户该项目已经存在,否则将此项目添加到 DB.. 我确实发胖了下面的代码,但它不起作用,它会打印两个条件 if 语句

 <?php session_start(); include "connect.php"; $access = isset($_SESSION["userid"]); if ($access) { $itemid = filter_input(INPUT_GET, "itemid", FILTER_VALIDATE_INT); if($itemid?== null && $itemid;== false){ $SQL = $dbh->prepare("SELECT * FROM sales where userid =;"); if($SQL->execute([$_SESSION["userid"]])){ if ($SQL->rowCount() > 0){ while($row = $SQL->fetch()){ if((int)$row['itemid'] === $itemid){ echo "item is exist"; }else{ echo "add it to the table"; } } } } } }

You're reporting "add it to the table" for every row that has a different item ID.您正在为具有不同项目 ID 的每一行报告“将其添加到表中”。 You can't know that the item ID isn't found until you get to the end of the loop, if it was never matched.如果项目 ID 从未匹配,则在循环结束之前,您无法知道项目 ID 未找到。 See Searching array reports "not found" even though it's found for this general problem, which is a common beginner error.请参阅搜索数组报告“未找到”,即使已找到此一般问题,这是一个常见的初学者错误。

But there's no need for the loop.但是不需要循环。 Check for itemid in the SQL query.检查 SQL 查询中的itemid

$SQL = $dbh->prepare("SELECT COUNT(*) as count FROM sales where userid = ? and itemid = ?");
$SQL->execute([$_SESSION['userid'], $itemid]);
$row = $SQL->fetch();
if ($row['count'] > 0) {
    echo "item is exist";
} else {
    echo "add it to the table";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM