Page 1 sur 1

Requete liée sur deux tables

Posté : 24 janv. 2009, 11:06
par Laurent75017
Bonjour,
Je veux créer une sorte de blog où s'affiche différentes photos avec possibilité de laisser des commentaires sur les photos.

J'ai une table "Oscarblog" ou je stocke les infos relative à mes photos :

-id
-photo
- titre
-...

Et une autre table "OscarblogComment" où je stocke les commentaires :

-reference
-commentaire

Je veux afficher les photos les unes aprés les autres (région répétée) avec les commentaires de celles qui en possede.

Voici ma requete :

SELECT *
FROM Oscarblog LEFT JOIN OscarblogComment ON Oscarblog.id = OscarblogComment.reference
ORDER BY `date` DESC

Probleme : Ma requete fonctionne bien sauf qu'elle me sort 3 fois la photo 1 s'il y a 3 commentaires pour la 1.


Est ce que quelqu'un aurai une idée?

Merci

Posté : 25 janv. 2009, 15:08
par furiouslol
Salut

Si ton but est d'afficher toutes tes photos et tous tes commentaires, ta requete est bonne (si ce n'est qu'il vaut toujours mieux préciser les champs du selct plutot que de mettre une etoile)
A toi de faire le traitement adéquat en php au moment de l'affichage

Comment?

Posté : 26 janv. 2009, 14:25
par Laurent75017
Salut,
Je ne comprends pas à quel moment je dois demander de n'afficher qu'une seule fois la photo (celle où il y a plusieurs commentaires)

Peux tu m'expliquer? Merci


mon code :
<?php require_once('../Connections/basemillimetre.php'); ?>
<?php require_once('../Connections/basemillimetre.php'); ?>
<?php require_once('../Connections/basemillimetre.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$currentPage = $_SERVER["PHP_SELF"];

$maxRows_oscar = 10;
$pageNum_oscar = 0;
if (isset($_GET['pageNum_oscar'])) {
  $pageNum_oscar = $_GET['pageNum_oscar'];
}
$startRow_oscar = $pageNum_oscar * $maxRows_oscar;

mysql_select_db($database_basemillimetre, $basemillimetre);
$query_oscar = "SELECT * FROM Oscarblog LEFT JOIN OscarblogComment ON Oscarblog.id = OscarblogComment.reference ORDER BY `date` DESC";
$query_limit_oscar = sprintf("%s LIMIT %d, %d", $query_oscar, $startRow_oscar, $maxRows_oscar);
$oscar = mysql_query($query_limit_oscar, $basemillimetre) or die(mysql_error());
$row_oscar = mysql_fetch_assoc($oscar);

if (isset($_GET['totalRows_oscar'])) {
  $totalRows_oscar = $_GET['totalRows_oscar'];
} else {
  $all_oscar = mysql_query($query_oscar);
  $totalRows_oscar = mysql_num_rows($all_oscar);
}
$totalPages_oscar = ceil($totalRows_oscar/$maxRows_oscar)-1;

mysql_select_db($database_basemillimetre, $basemillimetre);
$query_categorie = "SELECT distinct`categorie` FROM Oscarblog";
$categorie = mysql_query($query_categorie, $basemillimetre) or die(mysql_error());
$row_categorie = mysql_fetch_assoc($categorie);
$totalRows_categorie = mysql_num_rows($categorie);

$colname_souscategorie = "-1";
if (isset($_GET['categorie'])) {
  $colname_souscategorie = $_GET['categorie'];
}
mysql_select_db($database_basemillimetre, $basemillimetre);
$query_souscategorie = sprintf("SELECT distinct`souscategorie`,`categorie` FROM Oscarblog WHERE categorie = %s ORDER BY `date` DESC", GetSQLValueString($colname_souscategorie, "text"));
$souscategorie = mysql_query($query_souscategorie, $basemillimetre) or die(mysql_error());
$row_souscategorie = mysql_fetch_assoc($souscategorie);
$totalRows_souscategorie = mysql_num_rows($souscategorie);

mysql_select_db($database_basemillimetre, $basemillimetre);
$query_commentaire = "SELECT * FROM OscarblogComment, Oscarblog WHERE `OscarblogComment`.reference = `Oscarblog`.id";
$commentaire = mysql_query($query_commentaire, $basemillimetre) or die(mysql_error());
$row_commentaire = mysql_fetch_assoc($commentaire);
$totalRows_commentaire = mysql_num_rows($commentaire);

$queryString_oscar = "";
if (!empty($_SERVER['QUERY_STRING'])) {
  $params = explode("&", $_SERVER['QUERY_STRING']);
  $newParams = array();
  foreach ($params as $param) {
    if (stristr($param, "pageNum_oscar") == false && 
        stristr($param, "totalRows_oscar") == false) {
      array_push($newParams, $param);
    }
  }
  if (count($newParams) != 0) {
    $queryString_oscar = "&" . htmlentities(implode("&", $newParams));
  }
}
$queryString_oscar = sprintf("&totalRows_oscar=%d%s", $totalRows_oscar, $queryString_oscar);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Le Blog d'Oscar</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="CSS.css" rel="stylesheet" type="text/css">
<style type="text/css">
<!--
a:link {
	color: #333333;
	text-decoration: none;
}
a:visited {
	text-decoration: none;
	color: #333333;
}
a:hover {
	text-decoration: none;
	color: #666666;
}
a:active {
	text-decoration: none;
	color: #666666;
}
.Style1 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 12px;
	color: #333333;
}
.Style4 {
	font-size: 12pt;
	font-family: Arial, Helvetica, sans-serif;
	color: #333333;
}
-->
</style>
<script type="text/javascript">
<!--
function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}
//-->
</script>
</head>

<body bgcolor="#000000" text="#666666">
<div align="center">
  <p>&nbsp;</p>
  <table width="800" border="0" cellspacing="0" cellpadding="0">
    <tr> 
      <td><img src="Images/OSCAR578.jpg" width="800" height="314"></td>
    </tr>
    <tr>
      <td><table width="800" border="0" cellspacing="10" cellpadding="0">
        <tr>
          <td align="left" valign="top" class="arial12gris"><div align="justify">Bienvenue sur mon blog. Il y a, &agrave; ce jour, <strong><?php echo $totalRows_oscar ?></strong> photos que vous pouvez consulter et imprimer &agrave; votre guise. Vous pouvez faire d&eacute;filer mes photos une &agrave; une ou choisir une cat&eacute;gorie en particulier. </div></td>
          <td align="left" valign="top" class="arial12gris"><form name="form2" method="post" action="">
            <label>
            <select name="jumpMenu2" id="jumpMenu2" onChange="MM_jumpMenu('parent',this,0)">
              <option value="#" selected="selected">Aller directement &agrave; la cat&eacute;gorie...</option>
              <?php
do {  
?>
              <option value="categorie.php?categorie=<?php echo $row_categorie['categorie']?>"><?php echo $row_categorie['categorie']?></option>
              <?php
} while ($row_categorie = mysql_fetch_assoc($categorie));
  $rows = mysql_num_rows($categorie);
  if($rows > 0) {
      mysql_data_seek($categorie, 0);
	  $row_categorie = mysql_fetch_assoc($categorie);
  }
?>
              <option value="videos.php">Mes vidéos...</option>
            </select>
            </label>
          </form></td>
        </tr>
      </table></td>
    </tr>
    <tr>
      <td height="80" align="center" valign="middle" class="lignegrisebas"><table width="100%" border="0">
          <tr>
            <td width="20%" align="left" valign="middle" class="arial12gris"><?php if ($pageNum_oscar > 0) { // Show if not first page ?>
                  <a href="<?php printf("%s?pageNum_oscar=%d%s", $currentPage, 0, $queryString_oscar); ?>"><img src="First.gif" border=0 align="texttop"> PREMI&Egrave;RES PHOTOS</a>
            <?php } // Show if not first page ?></td>
            <td width="20%" align="left" valign="middle" class="arial12gris"><?php if ($pageNum_oscar > 0) { // Show if not first page ?>
                  <a href="<?php printf("%s?pageNum_oscar=%d%s", $currentPage, max(0, $pageNum_oscar - 1), $queryString_oscar); ?>"><img src="Previous.gif" border=0 align="texttop"> PHOTOS PR&Eacute;C.</a>
            <?php } // Show if not first page ?>            </td>
            <td width="20%" align="center" valign="middle" class="arial12gris">&nbsp;
Photos <?php echo ($startRow_oscar + 1) ?> &agrave; <?php echo min($startRow_oscar + $maxRows_oscar, $totalRows_oscar) ?> sur <?php echo $totalRows_oscar ?> </td>
            <td width="20%" align="right" valign="middle" class="arial12gris"><?php if ($pageNum_oscar < $totalPages_oscar) { // Show if not last page ?>
                  <a href="<?php printf("%s?pageNum_oscar=%d%s", $currentPage, min($totalPages_oscar, $pageNum_oscar + 1), $queryString_oscar); ?>">PHOTOS SUIV. <img src="Next.gif" border=0 align="texttop"></a>
            <?php } // Show if not last page ?>            </td>
            <td width="20%" align="right" valign="middle" class="arial12gris"><?php if ($pageNum_oscar < $totalPages_oscar) { // Show if not last page ?>
                  <a href="<?php printf("%s?pageNum_oscar=%d%s", $currentPage, $totalPages_oscar, $queryString_oscar); ?>">DERNI&Egrave;RES PHOTOS <img src="Last.gif" border=0 align="texttop"></a>
            <?php } // Show if not last page ?>            </td>
          </tr>
      </table></td>
    </tr>
    <tr>
      <td><?php do { ?>
          <table width="800" border="0" cellspacing="10" cellpadding="0">
            <tr>
              <td width="500" rowspan="3" align="left" valign="top"><a href="photos/<?php echo $row_oscar['nomphoto']; ?>"><img src="photos/<?php echo $row_oscar['nomphoto']; ?>" width="500" border="0" class="cadreblanc"></a></td>
              <td width="300" colspan="2" align="left" valign="top"><strong><span class="arial20gris"><?php echo $row_oscar['titre']; ?></span></strong><br>
                <span class="arial12gris"><?php echo $row_oscar['soustitre']; ?></span><br>
                <br>
                <div align="justify"><span class="arial12grisclair"><?php echo $row_oscar['texte']; ?></span><br>
                </div></td>
            </tr>
            <tr>
              <td align="left" valign="bottom" class="Style1">Cat&eacute;gorie :<br>
                <a href="categorie.php?categorie=<?php echo $row_oscar['categorie']?>"><span class="arial12gris" onMouseOver="this.style.color='#CCCCCC'" onMouseOut="this.style.color='#666666'"><?php echo $row_oscar['categorie']; ?></span></a><br>
				Sous cat&eacute;gorie :<br>
			    <a href="souscategorie.php?categorie=<?php echo $row_oscar['categorie']; ?>&souscategorie=<?php echo $row_oscar['souscategorie']; ?>"><span class="arial12gris" onMouseOver="this.style.color='#CCCCCC'" onMouseOut="this.style.color='#666666'"><?php echo $row_oscar['souscategorie']; ?></span></a></td>
              <td align="right" valign="bottom" class="Style1">Date :<br>
              <span class="arial12gris"><?php echo $row_oscar['date']; ?></span></td>
            </tr>
            <tr>
              <td colspan="2" align="left" valign="bottom" class="Style1"><table bgcolor="#333333" width="100%" border="0" cellspacing="0" cellpadding="0">
                <tr>
                  <td width="34%" height="20" align="center" valign="middle" class="arial12gris">Commentaires </td>
                  <td align="left" valign="top" bgcolor="#000000" class="arial12blanc">&nbsp;</td>
                </tr>
                <tr>
                  <td colspan="2" align="left" valign="top" class="arial12blanc"><table width="100%" border="0" cellspacing="5" cellpadding="0">
                    <tr>
                      <td align="left" valign="top" class="arial12grisclair"><?php echo $row_oscar['commentaire']; ?></td>
                    </tr>
                    <tr>
                      <td align="right" valign="top" class="arial12gris"><?php echo $row_oscar['auteur']; ?></td>
                    </tr>
                    <tr>
                      <td align="right" valign="top" class="arial10blanc"><table width="100%" border="0" cellspacing="0" cellpadding="0">
                        <tr>
                          <td align="left" valign="middle"><a href="postcommentaire.php?id=<?php echo $row_oscar['id']; ?>"><span class="arial10gris" onMouseOver="this.style.color='#CCCCCC'" onMouseOut="this.style.color='#666666'">Poster un commentaire</span></a></td>
                          <td align="center" valign="middle">l</td>
                          <td align="right" valign="middle"><a href="commentaires.php?reference=<?php echo $row_oscar['reference']; ?>"><span class="arial10gris" onMouseOver="this.style.color='#CCCCCC'" onMouseOut="this.style.color='#666666'">tous les commentaires</span></a></td>
                        </tr>
                      </table></td>
                    </tr>
                  </table></td>
                </tr>
              </table></td>
            </tr>
          </table>
          <table width="800" border="0" cellspacing="0" cellpadding="0">
            <tr>
              <td>&nbsp;</td>
            </tr>
          </table>
          <?php } while ($row_oscar = mysql_fetch_assoc($oscar)); ?></td>
    </tr>
    <tr> 
      <td height="80" align="center" valign="middle" class="lignegrisebas"><table width="100%" border="0">
        <tr>
          <td width="20%" align="left" valign="middle" class="arial12gris"><?php if ($pageNum_oscar > 0) { // Show if not first page ?>
              <a href="<?php printf("%s?pageNum_oscar=%d%s", $currentPage, 0, $queryString_oscar); ?>"><img src="First.gif" border=0 align="texttop"> PREMI&Egrave;RES PHOTOS</a>
            <?php } // Show if not first page ?></td>
          <td width="20%" align="left" valign="middle" class="arial12gris"><?php if ($pageNum_oscar > 0) { // Show if not first page ?>
              <a href="<?php printf("%s?pageNum_oscar=%d%s", $currentPage, max(0, $pageNum_oscar - 1), $queryString_oscar); ?>"><img src="Previous.gif" border=0 align="texttop"> PHOTOS PR&Eacute;C.</a>
              <?php } // Show if not first page ?>
          </td>
          <td width="20%" align="center" valign="middle" class="arial12gris">Photos <?php echo ($startRow_oscar + 1) ?> &agrave; <?php echo min($startRow_oscar + $maxRows_oscar, $totalRows_oscar) ?> sur <?php echo $totalRows_oscar ?> </td>
          <td width="20%" align="right" valign="middle" class="arial12gris"><?php if ($pageNum_oscar < $totalPages_oscar) { // Show if not last page ?>
              <a href="<?php printf("%s?pageNum_oscar=%d%s", $currentPage, min($totalPages_oscar, $pageNum_oscar + 1), $queryString_oscar); ?>">PHOTOS SUIV. <img src="Next.gif" border=0 align="texttop"></a>
              <?php } // Show if not last page ?>
          </td>
          <td width="20%" align="right" valign="middle" class="arial12gris"><?php if ($pageNum_oscar < $totalPages_oscar) { // Show if not last page ?>
              <a href="<?php printf("%s?pageNum_oscar=%d%s", $currentPage, $totalPages_oscar, $queryString_oscar); ?>">DERNI&Egrave;RES PHOTOS <img src="Last.gif" border=0 align="texttop"></a>
              <?php } // Show if not last page ?>
          </td>
        </tr>
      </table></td>
    </tr>
    <tr> 
      <td height="50" align="center" valign="middle"><table border="0" cellspacing="10" cellpadding="0">
        <tr>
          <td align="center" valign="middle" class="arial12gris"><a href="connexion.php">CONNEXION</a></td>
          <td align="center" valign="middle"><span class="Style4">|</span></td>
          <td align="center" valign="middle" class="arial12gris"><a href="ajoutphoto.php">AJOUTER UNE NOUVELLE PHOTO</a></td>
          <td align="center" valign="middle" class="arial12gris"><span class="Style4">|</span></td>
          <td align="center" valign="middle" class="arial12gris"><a href="selectnote.php">MODIFIER UNE NOTE</a></td>
          <td align="center" valign="middle" class="arial12gris"><span class="Style4">|</span></td>
          <td align="center" valign="middle" class="arial12gris"><form name="form1" method="post" action="">
              <label>
              <select name="jumpMenu" id="jumpMenu" onChange="MM_jumpMenu('parent',this,0)">
                <option value="#" selected="selected">Aller directement &agrave; la cat&eacute;gorie...</option>
                <?php
do {  
?>
                <option value="categorie.php?categorie=<?php echo $row_categorie['categorie']?>"><?php echo $row_categorie['categorie']?></option>
                <?php
} while ($row_categorie = mysql_fetch_assoc($categorie));
  $rows = mysql_num_rows($categorie);
  if($rows > 0) {
      mysql_data_seek($categorie, 0);
	  $row_categorie = mysql_fetch_assoc($categorie);
  }
?>
<option value="videos.php">Mes vidéos...</option>
              </select>
              </label>
          </form></td>
        </tr>
      </table></td>
    </tr>
  </table>
</div>
</body>
</html>
<?php
mysql_free_result($oscar);

mysql_free_result($categorie);

mysql_free_result($souscategorie);

mysql_free_result($commentaire);

?>

Posté : 28 janv. 2009, 21:44
par furiouslol
Peux tu m'expliquer? Merci
Pas de soucis, par contre me demande pas de lire ton pavé de code :wink:

Voila le tableau PHP que tu dois obtenir a la sortie d'une requete comme la tienne :

Code : Tout sélectionner

id | photo | id_commentaire | commentaire 1 truc.jpg 1 premiere photo 1 truc.jpg 2 deuxieme commentaire sur truc 2 machin.jpg 3 commentaire machin
Ce tableau tu dois le parcourir ligne par ligne pour construire ton affichage, et n'afficher l'image que lorsque la ligne contient un id de photo nouveau
$oldId = -1
foreach (ton tableau s'appellera $row dans cet exemple)
{
  if ( $oldID == -1 ou $row["id"]!=$oldRow)
  {
    //<afficher la photo et aller a la ligne>
  }
  
  //<afficher la ligne de commentaire contenu dans row et aller la la ligne>

  $oldID = $row["id"];
}
Avec l'exemple du tableau au dessus, au premier tour dans la boucle, on aura $oldID == 0 , donc ca affichera l'image, et le comemntaire n°1
Au deuxieme tour, $oldID vaudra 1, et sera egal a $row["id"], l'image ne sera pas affichée et tu affichera le commentaire N°2
Au troisieme tour $oldId vaudra 2, et sera donc different de row["id"] qui vaudra 3, l'image sera affichée et tu affichera a la suite le commentaire 3