简体   繁体   English

PHP:检查SQL表中两个列值是否正确

[英]PHP : Check If Two Column-Values are Correct in SQL Table

I want to check an SQL table if two column values are both equal to specified values using PHP. 我想检查SQL表,如果两个列值都等于使用PHP指定的值。 My table looks like this: 我的桌子看起来像这样:

             my_db 
------------------------------------------
 code       | user | email               |
------------------------------------------
 10314343   |  20  | example@example.com |
 13423434   |  22  | example@example.com |
 11342434   |  40  | example@example.com |

This is my PHP, although not working: 这是我的PHP,尽管不起作用:

// Set variables
$tbl_name = mydb;
$matchCode   = "10314343"
$matchUserID = "20"

// Query matchCode and MatchUSerID on db
$getName = "SELECT FROM $tbl_name WHERE user ='$matchUserID' ";
$queryName = mysql_query($getName);

// Query matchCode and MatchUSerID on db
$getCode = "SELECT FROM $tbl_name WHERE code ='$matchCode' ";
$queryCode = mysql_query($getCode);


// If these match 
if($queryCode == 1 || $queryName == 1) {
  echo "The User ID and Code Value Both Match";
}

I'm not sure whether this is the best way of doing things. 我不确定这是否是最好的处理方式。 I was thinking you might be able to get the entire row data by "user" ID, and then query that row for the "code" value. 我以为您可能可以通过“用户” ID获取整个行数据,然后在该行中查询“代码”值。 Although I'm unsure how to do that. 尽管我不确定该怎么做。

What I'm trying to achieve is an sql query that checks if my variable matches the data of "code" for in the row of $matchUserID . 我想要实现的是一个SQL查询,该查询检查我的变量是否与$matchUserID行中的“代码”数据匹配。

You're not selecting anything, also if you want to check if both values are the same in 1 row, you should combine the queries: 您没有选择任何内容,如果您想检查两个值是否在1行中相同,则应合并查询:

$sql = "SELECT COUNT(*) FROM $tbl_name WHERE user ='$matchUserID' AND code = '$matchCode'";
$result = mysql_query($sql) or die(mysql_error());
$hasMatch = mysql_result($result, 0);
if ($hasMatch) {
    ...
}

Since you're only interested in knowing whether a row exists in the table, you can use COUNT(*) to only return the number of rows that were found. 由于您只想知道表中是否存在行,因此可以使用COUNT(*)仅返回找到的行数。

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

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