如何使用字符串调节选项从mysql DB中获取数据?

时间:2018-01-08 05:09:29

标签: php mysql

在我的项目中,我想从DB获取title,dep和name,条件选项是id_select。

id_select成功来自BB表。代码是:

$sql="select sNum from BB where id='TN001';";
$sel = $conn->query($sql);

$resSQL =  $conn->query($sql)->fetchall();

if(count($resSQL) > 0)
{              
   while($numRow=$sel->fetch(PDO::FETCH_NUM))
   {
     $systemNum[]=$numRow[0];
   }
}   
   $id_select=implode(",",$systemNum);

条件选项的内容" id_select"字符串就像:

N20180004,N20180005,N20180006,N20180007,N20180008,N20180009

" id_select"在sql中用作调节选项。代码是:

 $sql="select title,dep,name from  OA where sysid in ($id_select);";//works fail

title,dep,name的正确输出应为:

 ncss,hpc,Tom      //for N20180004
 ncss,cloude,Jack  //for N20180005
 ncss,market,Stock //for N20180006
 ncss,system,Stack //for N20180007
 ncss,project,Shansa //for N20180008
 ncss,administr,Go  //for N20180009

最后,它们应该存储在数据数组中。但不幸的是,它失败了,没有任何回报。

所以,我尝试了另一个sql:

$sql="select title,dep,name from  OA  where name='Tom';"; //works ok

$sql="select title,dep,name from  OA where sysid='N20180009';";//works ok

它们都可以和一条返回记录一起使用。

PHP的总代码是:

$sql="select sNum from BB where id='TN001';";
$sel = $conn->query($sql);

 $resSQL =  $conn->query($sql)->fetchall();

 if(count($resSQL) > 0)
 {              
   while($numRow=$sel->fetch(PDO::FETCH_NUM))
  {
   $systemNum[]=$numRow[0];
   }
 }   
 $id_select=implode(",",$systemNum);

 $cdata=array();

 $sql="select title,dep,name from  OA where sysid in ($id_select);";//works fail
 //$sql="select title,dep,name from  OA  where name='Tom';"; //works ok
 //$sql="select title,dep,name from  OA where sysid='N20180009';";//works ok
   $sel=$conn->query($sql);

   while($res=$sel->fetch(PDO::FETCH_BOTH)){
     $cdata[]=$res;
   }

  $data=array();

 foreach($cdata as $k=>$v){
  $data['rows'][$k]['SNV']=$v['title'];
  $data['rows'][$k]['CV']=$v['dep'];
  $data['rows'][$k]['EV']=$v['name'];
  }

  $data['total']=$row[0];  
  echo json_encode($data);

在我的项目中,我不得不选择id_select选项。谁能帮帮我?

2 个答案:

答案 0 :(得分:1)

由于您的$id_selectstrings为每个' PHP添加了撇号row

while($numRow=$sel->fetch(PDO::FETCH_NUM))
{
  $systemNum[] = "'".$numRow[0]."'";
}

$id_select=implode(",",$systemNum);之后$id_select将如下所示:

'N20180004','N20180005','N20180006','N20180007','N20180008','N20180009','N20180010' 

从我看到的一切都应该可以正常工作。

答案 1 :(得分:0)

$ sql =“SELECT title,dep,OA中的名称其中sysid IN(”。implode(',',$ id_select)。“)”;

我认为这对你很有帮助。