-1

I'm trying to get a certain data from mysql with fetchAll.

I currently have this:

$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);  
}

My comments is output all the columns in my database. What if I only want comments,time,id,etc... how would I distinguish this in this syntax?

Thanks in advance!

4

2 回答 2

1

When querying a SQL database, SELECT statements should also include a list of columns you want returned. This not only saves time because the SQL database doesn't have to retrieve a list of columns on each query, but it requires you to think about what you need. In your case, if you only want: comments, time, id then you should specify it:

$comments= $dbh->prepare("SELECT id, time FROM comments WHERE idinformation= ?");
于 2012-06-21T04:12:55.703 回答
1

Change the line

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

to

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

Edit:

Alternatively use group_concat(comments time id, ', ') in a single SQL query. You could do this as a single "JOIN"ed query, and group_concat the comments if you can get the separator you need. Everything is then done SQL-side = faster.

Documentation: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

于 2012-06-21T04:13:15.250 回答