我的主页正在显示一张表,该表带有基于当前用户的团队从DB中获取的不同数据。当用户在显示桌子时正在阅读的用户登录时,我正在与团队创建cookie。
当用户未登录时,我也想显示表,但是我希望它显示2个(或更多)团队的数据。我目前正在使用临时解决方案使用Null Cocce运算符,该操作员默认为一线队,看起来像:$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时,哪个工作...我尝试了其他的其他变体,但无法使其起作用。有任何想法吗?谢谢!
edit :我的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'
时,我不会从数据库中获得任何结果。我的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 );
您应该在,
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';