我的主页显示一个基于当前用户的团队从数据库中获取不同数据的表。当用户登录时,我正在为团队创建一个cookie,以便在显示表格时阅读。空合并运算符和SQL IN子句
当用户没有登录时,我也想显示该表,但我希望它显示2个(或更多)团队的数据。我使用的是临时的解决方案,现在使用空COALESCE运营商默认为一线队,看起来像这样:$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);
刚确保你使用的是什么版本的PHP? –
我正在运行PHP版本7.0.3的WAMP – IcedAnt
我通过参数化假设你的意思是准备好的语句。我意识到这一点,目前正在更新所有内容。至于你的建议,我不能说我确定你的意思。你能扩展还是提供一个例子?谢谢! – IcedAnt