在php中使用不同的id获取mysql单个查询中的多行

时间:2018-02-17 07:53:25

标签: php mysql json database

我有不同的ID,我从用户

获取这些ID的值
$id=array();
$id[0]=$_GET["id0"];
$id[1]=$_GET["id1"];
$id[2]=$_GET["id2"];

现在从数据库中获取数据我正在使用以下查询:

for($j=0;$j<count($id);$j++)
{
  $res=mysql_query("SELECT * FROM mutable WHERE id='$id[$j]'")
  while($row=mysql_fetch_array($res))
  {
     $row[]=array("email"=>$row[2],"name"=>$row[3],"address"=>$row[5]);
     echo JSON_encode($row);
  }
}

现在我使用for循环从这个查询获得了正确的结果,但结果不是正确的JSON格式,有没有办法更有效地做到这一点并在JSON数组和JSON对象格式中获得正确的结果

3 个答案:

答案 0 :(得分:0)

json_encode()放在你的循环之外。

让我们现代化和改进事物......

*不幸的是,使用IN子句的预准备语句会受到卷积的影响。 pdo不会以同样的方式受到影响。

代码:(未经测试)

if(isset($_GET['id0'],$_GET['id1'],$_GET['id2'])){
    $params=[$_GET['id0'],$_GET['id1'],$_GET['id2']];  // array of ids (validation/filtering can be done here)
    $count=count($params);  // number of ids
    $csph=implode(',',array_fill(0,$count,'?'));  // comma-separated placeholders
    $query="SELECT * FROM mutable WHERE id IN ($csph)";

    $stmt=$mysqli->prepare($query);  // for security reasons

    array_unshift($params,str_repeat('s',$count));  // prepend the type values string
    $ref=[];  // add references
    foreach($params as $i=>$v){
        $ref[$i]=&$params[$i];  // pass by reference as required/advised by the manual
    }
    call_user_func_array([$stmt,'bind_param'],$ref);    

    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_array(MYSQLI_NUM))
        $rows=["email"=>$row[2],"name"=>$row[3],"address"=>$row[5]];
    }
    $stmt->close();
    echo json_encode($rows);
}

答案 1 :(得分:0)

三件事:

  1. 处理不受信任(即$_GET)输入时,始终始终使用prepared statements和绑定参数。就这么做。

  2. 关于您使用JSON的问题,您只需运行json_encode一次:

    $results = [];
    for($j=0;$j<count($id);$j++) {
        ...
        while($row=mysql_fetch_array($res)) {
            results[] = ...
        }
    }
    json_encode( $results );
    
  3. 使用单个SQL语句,因为您要收集已知数量的ID:

    $dbh = new PDO($dsn, $user, $password);
    $sql = "SELECT * FROM mutable WHERE id IN (?, ?, ?)";
    $sth = $dbh->prepare( $sql );
    foreach ( $sth->execute( [$_GET['id0'], $_GET['id1'], $_GET['id2']] ) as $row ) {
        ...
    

    这比数据库的多次往返更有效。对于这种人为的情况,这可能并不重要,但从长远来看,养成良好的习惯会为你服务。

答案 2 :(得分:0)

你错误地使用了$row,在循环之外声明了数组变量,如

    $json_response = array();
    for($j=0;$j<count($id);$j++) {
        $res=mysql_query("SELECT * FROM mutable WHERE id='$id[$j]'")
        while($row=mysql_fetch_array($res)) {
            $json_response[]=array("email"=>$row[2],"name"=>$row[3],"address"=>$row[5]);
            echo json_encode($json_response); // not good to echo here
        }
    }
    // echo json_encode($json_response); // ideally echo should be here