Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用PDO fetchAll在数组中选择mysql数据_Php_Mysql_Arrays_Json_Pdo - Fatal编程技术网

Php 使用PDO fetchAll在数组中选择mysql数据

Php 使用PDO fetchAll在数组中选择mysql数据,php,mysql,arrays,json,pdo,Php,Mysql,Arrays,Json,Pdo,我正在尝试使用fetchAll从mysql获取特定数据 我目前有: $sql1= $dbh->query("SELECT * FROM information"); $comments= $dbh->prepare("SELECT * FROM comments WHERE idinformation= ?"); if($retail){ while($row = $retail -> fetch(PDO::FETCH_ASSOC)){ $comments->exec

我正在尝试使用fetchAll从mysql获取特定数据

我目前有:

$sql1= $dbh->query("SELECT * FROM information");
$comments= $dbh->prepare("SELECT * FROM comments WHERE idinformation= ?");
if($retail){
while($row = $retail -> fetch(PDO::FETCH_ASSOC)){
  $comments->execute(array($row['idproducts']));
  $json['data'][] = array(
     'id'=>$row['idproducts'],
     "headline"=>$row['headline'],
     'price'=> array ("full_price" => $row['full_price']),
     'description'=>$row['description'],
     "comments" => $comments->fetchAll(PDO::FETCH_ASSOC)
);
}
$json_encode = json_encode($json);
$obj = json_decode($json_encode,true);  
}
我的注释将输出到数据库中的所有列。如果我只想要评论、时间、id等怎么办。。。在这种语法中,我如何区分这一点


提前谢谢

查询SQL数据库时,SELECT语句还应包含要返回的列的列表。这不仅节省了时间,因为SQL数据库不必在每个查询中检索列列表,而且还需要考虑需要什么。在您的情况下,如果您只需要:注释、时间、id,那么您应该指定它:

$comments= $dbh->prepare("SELECT id, time FROM comments WHERE idinformation= ?");
换线

$comments= $dbh->prepare("SELECT * FROM comments WHERE idinformation= ?"); 

编辑:

或者,在单个SQL查询中使用组_concatcomments time id“,”。您可以将其作为一个单独的联合查询来执行,如果可以获得所需的分隔符,则可以对注释进行分组。然后一切都完成了,SQL端=更快


文档:

而不是*在查询中写入列名。
$comments= $dbh->prepare("SELECT comments,time,id FROM comments WHERE idinformation= ?");