提问人:Desarrollo Creo 提问时间:8/15/2023 最后编辑:Desarrollo Creo 更新时间:8/15/2023 访问量:57
为什么爆炸会在一段时间内显示上述结果 php
Why explode shows the above results in a while php
问:
我在一段时间内做了一个爆炸,用逗号(,)分隔单词并修复它,以便它可以放在sql查询中,在while的第一个示例中,它正确地输出了我想要的内容,但在while的第二次迭代中,它显示了前一个输出的单词:
$queryselectprocesses ="SELECT * FROM laziness_config_processes WHERE busid = $buss ";
$execqueryselectprocesses = sqlsrv_query($con_laziness, $queryselectprocesses);
while($fila = sqlsrv_fetch_array($execqueryselectprocesses,SQLSRV_FETCH_ASSOC)){
$modalities_select = $fila['modalities'];
$institutions_select = $fila['institutions'];
#the 导致 $modalities_select = AB, CD 的 while 的第一个输出
#the 结果为 $institutions_select = CAR, MOTORCYCLE 的第一个 while 输出
#the 导致 $modalities_select = FG, HI 的 while 的第二个输出
#the 导致 $institutions_select = BIKE, HELMET 的第二个 while 输出
$queryselectprocesses ="SELECT * FROM laziness_config_processes WHERE busid = $buss ";
$execqueryselectprocesses = sqlsrv_query($con_laziness, $queryselectprocesses);
while($fila = sqlsrv_fetch_array($execqueryselectprocesses,SQLSRV_FETCH_ASSOC)){
$modalities_select = $fila['modalities'];
$institutions_select = $fila['institutions'];
$mods = explode(',', $modalities_select);
for ($i = 0; $i < count($mods); $i++){
$mods[$i] = trim($mods[$i]);
}
foreach ($mods as $value) {
if ($value != '-1' and trim($value) != '') {
$mod .= "'" . trim($value). "',";
}
}
if (trim($mod) != '') {
$mod = substr($mod, 0, strlen($mod)-1);
$mod = " modality in ( $mod ) ";
}
$insts = explode(',', $institutions_select);
for ($i = 0; $i < count($insts); $i++){
$insts[$i] = trim($insts[$i]);
}
foreach ($insts as $value) {
if ($value != '-1' and trim($value) != '') {
$inst .= "'" . trim($value). "',";
}
}
if (trim($inst) != '') {
$inst = substr($inst, 0, strlen($inst)-1);
$inst = " institution in ( $inst ) ";
}
$query = " select * from tb_model where $mod and $inst ";
echo $query;
}
#The 结果是第一个 while 输出 $query = select * from tb_study where modality in ( 'AB','CD' ) 和 institution in ( 'CAR', 'MOTO' )
#但是,$query = 从 tb_study 中选择 * 的第二个输出的结果,其中模态在 ( 模态在 ( 'AB','CD' ) 'FG','HI' ) 和 institution in ( institution in ( 'CAR','MOTORCYCLE' ) 'BIKE','HELMET' )
#The 结果应该在 $query while 的 while 的第二个输出中输出 = select * from tb_study where modity in ( 'FG','HI' ) 和 institution in ( 'BICYCLE','HELMET' ) )
答:
您必须在 while 循环开始时重置$mod。此代码说明了您的问题。
<?php
$showcase = function($resetMod = false) {
$step = 0;
$mod = '';
while($step++ < 2) {
if($resetMod) {
$mod = '';
}
for($i = 0; $i < 2; $i++) {
$mod .= $i;
}
echo $mod . ' ';
}
};
echo $showcase();
echo "\r\n";
echo $showcase(true);
此外,还应考虑使用预准备语句,而不是通过字符串插值来构建$query。https://stackoverflow.com/a/24989031/14008536
评论
它是通过将其添加到while的开头来解决的,如下所示:
while($fila = sqlsrv_fetch_array($execqueryselectprocesses,SQLSRV_FETCH_ASSOC)){
$mod = '';
$inst = '';
但是,如果我做准备好的发言,谢谢朋友。
评论