Check if a certain element is in a table MySQL database

Viewed 21

I need to check if a certain element is in the table.

Table I am using:

+----------+------------+-------------------+
| ClientId | ClientName | ClientCountryName |
+----------+------------+-------------------+
|        1 | Chris      | UK                |
|        2 | David      | AUS               |
|        3 | Robert     | US                |
|        4 | Mike       | ENG               |
+----------+------------+-------------------+

This is the code I made, is there a better way?

$c=0;
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
    if('US'==$row['ClientCountryName']){
        $c=$c+1; //If the element is in the table, increment c
    }
}
if($c!=0){    //if c is incremented means that the element is one or multiple times in the table
    echo 'Element is in the table';
}
else{ //if c is not incremented then the element is not in the table
  ...
}
1 Answers

You can use count to return count of elements containing US

select count(*) 
from users 
where ClientCountryName like 'US'

Thanx!

Related