Borja
Borja

Reputation: 3559

Find value in column of MySQL table and print return

I have table cars and inside I have two fields year and chat_id

I have two records inside:

2019 | 1234
2018 | 1111

How can I search inside table chat_id == 1234 and return 1 if exist else 0? How can I print this?

I tried this but doesn't work:

$chat_id= 1234;

$query= "SELECT IF(chat_id == $chat_id,0,1) AS return FROM cars";
$return_id= mysqli_query($connection, $query);
print_r($return_id);

Upvotes: 0

Views: 54

Answers (2)

Dharman
Dharman

Reputation: 33375

To check for existence you do not need to select any data from the DB. You can just fetch 1 if it exists otherwise it will return NULL. Also you should always remember to use prepared statements and never inject PHP variables into SQL queries.

$chat_id = 1234;

$stmt = $connection->prepare('SELECT 1 FROM cars WHERE chat_id = ?');
$stmt->bind_param('i', $chat_id);
$stmt->execute();
// fetch the first column from the first row as an integer
$return_id = (int) $stmt->get_result()->fetch_row()[0];

Another option is to use bind_result as can be seen in this article: How to check whether a value exists in a database using mysqli prepared statements

Upvotes: 1

Samir Selia
Samir Selia

Reputation: 7065

You can use mysqli_num_rows to check if the record exists and WHERE clause to filter the results.

$chat_id= 1234;

$query= "SELECT chat_id FROM cars WHRE chat_id = '$chat_id'";
$return_id= mysqli_query($connection, $query);
$rowcount = mysqli_num_rows($return_id);
echo $rowcount; // Will return total number of rows matched else will return zero

Upvotes: 0

Related Questions