[英]Fetch multiple rows in mysql single query in php with different id
我有不同的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对象格式获得正确的结果
将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);
}
三件事:
在处理不可信(即$_GET
)输入时,始终, 始终 , 始终使用预处理语句和绑定参数。 去做就对了。
关于您的JSON问题,您只需运行一次json_encode
:
$results = []; for($j=0;$j<count($id);$j++) { ... while($row=mysql_fetch_array($res)) { results[] = ... } } json_encode( $results );
使用单个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 ) { ...
这比多次往返数据库更为有效。 对于这种人为的情况,可能并不重要,但是从长远来看,现在养成良好的习惯将为您服务。
您错误地使用了$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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.