简体   繁体   中英

Print only one result of a query using PHP and mySQL?

I am working with mySQL and PHP and I came across a query that is making think for the entire day, I'm not sure if my difficulties are with not knowing some advance command that might be requested for this, can you please help?

Here's the thing: I am working with an old database and I don't want to change the tables in it, so I got to work with two tables:

  • album: this table has only two fields, id_album and album_name;
  • photos: this table holds the photo's paths and it's linked to the album table by the field id_album;

I want to build a page that will list all the albums and each one will have a thumbnail, that I'm taking from the "photos" table, in that case, I need to list just one photo to each album, and I'm not sure how to write the code for that, this is what I got so far:

  <?php

  $comando = "SELECT * FROM album";

    $consulta = mysql_query($comando, $database)

        or die('Error:<br/>'.$comando);

    while($dados = mysql_fetch_array($consulta)) {


        $comando1 = "SELECT * FROM photos WHERE album = '".$dados['id_album']."'";
        $consulta1 = mysql_query($comando1, $database)
        or die('Error'.$comando1);

        while($dados1= mysql_fetch_array($consulta1)){          
          print '<li><a href="photos.php?Cod='.$dados['id_album'].'"><img src="'.$dados1['foto'].'"/></a><br/><a href="photos.php?Cod='.$dados['id_album'].'"> ' .$dados['album_name']. '</a></li>';

    }}

    ?>

It is working correctly but it is listing all photos in all albums. Is there a way that I can make it print just one photo for each album?

Thank you very very much in advance!

$comando1 = "SELECT * FROM photos WHERE album = '".$dados['id_album']."' LIMIT 1";

You should JOIN the queries. Use something like

$comando = "
   SELECT album.id_album, photos.* FROM `album` 
   LEFT JOIN `photos` on photos.album = album.id_album
   GROUP BY album.id_album";
while($dados = mysql_fetch_array($consulta)) {

$comando1 = "SELECT * FROM photos WHERE album = '".$dados['id_album']."' LIMIT 1 order by rand()";
$consulta1 = mysql_query($comando1, $database) or die('Error'.$comando1);

$dados1= mysql_fetch_row($consulta1);        
print '<li><a href="photos.php?Cod='.$dados['id_album'].'"><img src="'.$dados1['foto'].'"/></a><br/><a href="photos.php?Cod='.$dados['id_album'].'"> ' .$dados['album_name']. '</a></li>';

}

But you should really use MySqli or something else ..

Yes you use a single query with GROUP_CONCAT to get photos of album and SUBSTRING_INDEX to pick one photo

SELECT a.* ,SUBSTRING_INDEX(GROUP_CONCAT(p.foto),',',1) AS foto
FROM album a
LEFT JOIN photos p ON(a.id_album = p.id_album)
GROUP BY a.id_album

You can also specify ORDER BY in GROUP_CONCAT by your auto increment column in photos table to pick latest or first one as GROUP_CONCAT(p.foto ORDER BY p.id DESC) .Also as tadman mentioned in comments you are using depreciated mysql_* family functions better to start with PDO

<?php

$dbh = new PDO('mysql:host=yourhost;dbname=dbname', 'user', 'pass');
$sth = $dbh->prepare("SELECT a.* ,SUBSTRING_INDEX(GROUP_CONCAT(p.foto),',',1) AS foto
FROM album a
LEFT JOIN photos p ON(a.id_album = p.id_album)
GROUP BY a.id_album
");
$sth->execute();
$result = $sth->fetchAll(); 

foreach($result as $res){

  echo '<li><a href="photos.php?Cod='.$res['id_album'].'"><img src="'.$res['foto'].'"/></a><br/><a href="photos.php?Cod='.$res['id_album'].'"> ' .$res['album_name']. '</a></li>';
}
?>

PDO::errorInfo

Also during development you should care for errors before execute

$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES,false); 
if (!$sth) { 
    echo "\nPDO::errorInfo():\n"; 
    print_r($dbh->errorInfo()); 
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM