[英]MySQL update column and return value from another column in the same table
[英]Find value in column of MySQL table and print return
我有桌cars
,里面有兩個字段year
和chat_id
我里面有兩條記錄:
2019 | 1234
2018 | 1111
如何在表chat_id == 1234
內進行搜索,如果還存在0
,則返回1
? 我該如何打印?
我嘗試了這個,但是不起作用:
$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);
要檢查是否存在,您無需從數據庫中選擇任何數據。 您可以僅獲取1(如果存在),否則它將返回NULL
。 另外,您應該永遠記住使用准備好的語句,並且永遠不要將PHP變量注入SQL查詢中。
$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];
如本文中所見,另一個選擇是使用bind_result
: 如何使用mysqli預准備語句檢查數據庫中是否存在值
您可以使用mysqli_num_rows
檢查記錄是否存在,並使用WHERE
子句過濾結果。
$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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.