简体   繁体   中英

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. 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:

// 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. 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 .

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:

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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