[英]Null Coalesce Operator and SQL IN clause
我的主頁顯示的表格包含基於當前用戶團隊從數據庫中獲取的不同數據。 當用戶登錄時,我正在與團隊一起創建一個cookie,在顯示表格時我正在閱讀。
當用戶未登錄時,我也想顯示該表,但我希望它顯示2個(或更多)團隊的數據。 我正在使用臨時解決方案,現在使用null coalesce運算符,默認為第一個團隊,看起來像這樣: $team = $_COOKIE ['team'] ?? 1;
$team = $_COOKIE ['team'] ?? 1;
我的查詢: $associates = "SELECT associate_id, first_name, last_name FROM scp.associates WHERE team = '$team' ORDER BY associate_id ASC";
有沒有辦法修改其中一個或兩個以獲得我想要的輸出? 到目前為止,我嘗試過以下方法:
$team = $_COOKIE ['team'] ?? '1, 2';
$associates = "SELECT associate_id, first_name, last_name FROM scp.associates
WHERE team IN ('$team') ORDER BY team ASC, associate_id ASC";
如果設置了cookie,它可以工作,並且:
$team = $_COOKIE ['team'] ?? "'1', '2'";
$associates = "SELECT associate_id, first_name, last_name FROM scp.associates
WHERE team IN ($team) ORDER BY team ASC, associate_id ASC";
當沒有設置cookie時,它可以工作...我已經嘗試了其他變體,但無法使其工作。 有任何想法嗎? 謝謝!
編輯 :我的cookie是一個字符串,我現在正在使用預准備語句。 新代碼如下所示:
$team = $_COOKIE['team'] ?? '1';
$associates = "SELECT associate_id, first_name, last_name FROM scp.associates
WHERE team IN (?) ORDER BY team ASC, associate_id ASC";
$res_associates = odbc_prepare ( $conn, $associates );
odbc_execute ( $res_associates, array ( $team ) );
當我改為'1, 2'
,我沒有得到DB的結果。 我的if ( odbc_num_rows ( $res_associates ) > 0 )
是假的。
Edit2 :當我在查詢中直接添加值時,它可以工作但是當它從變量中獲取它們時(無論是否已准備好)它不會...
這樣可行:
$associates = "SELECT associate_id, first_name, last_name FROM scp.associates
WHERE team IN ('1', '2') ORDER BY team ASC, associate_id ASC";
但這不是:
$team = $_COOKIE['team'] ?? " '1', '2'";
$associates = "SELECT associate_id, first_name, last_name FROM scp.associates
WHERE team IN (?) ORDER BY team ASC, associate_id ASC";
(需要“和”之間的空格,所以它不認為它是一個文件)
方案 :
$team = $_COOKIE['team'] ?? '1,2';
$terms = explode ( ',', $team );
$placeholders = rtrim ( str_repeat ( '?, ', count ( $terms ) ), ', ' );
$associates = "SELECT associate_id, first_name, last_name FROM scp.associates
WHERE team IN ($placeholders) ORDER BY team ASC, associate_id ASC";
$res_associates = odbc_prepare ( $conn, $associates );
odbc_execute ( $res_associates, $terms );
您應該拆分a ,
s,將占位符放入查詢中,然后綁定每個術語。
類似的東西(我假設你正在使用PDO,如果沒有清空execute
調用並使用適當的調用你的驅動程序)這樣做:
$team = $_COOKIE['team'] ?? '1, 2';
$terms = explode(',', $team);
$placeholders = rtrim(str_repeat('?, ', count($terms)), ', ');
$associates = "SELECT associate_id, first_name, last_name
FROM scp.associates
WHERE team IN ($placeholders)
ORDER BY team ASC, associate_id ASC";
$get_stuff = $pdo->prepare($associates);
$get_stuff->execute($terms));
粗略演示: https : //3v4l.org/REqPc
這可能是一個類型問題,在解決此類問題時需要考慮的問題。 $_COOKIE ['team']
是什么類型的? 以及數據庫中team
類型是什么?
選項1:我認為PHP可能認為$_COOKIE ['team']
是一個int,它應該是一個字符串,它需要引號。 所以你可以做這樣的事情,它隱式地將它轉換為字符串並添加引號:
$team = $_COOKIE ['team'] ? "'" . $_COOKIE ['team'] . "'" : "'1', '2'";
選項2:在查詢中添加引號,如在第一個WHERE team IN ('$team')
,然后僅將其轉換為字符串。
$team = $_COOKIE ['team'] ? (string) $_COOKIE ['team'] : '1, 2';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.