Problème variable moteur de recvherche

Bonjour m'sieurs dâmes!

J' ai un petit soucis concernant un moteur de recherche interne que je suis en train d'essayer de faire.

Un formulaire genre "leboncoin" ou l' on peut changer les critères à volonté.

En prenant deux exemples du formulaires "mots clés" et "code postal".

L' un ou l' autre seul fonctionne mais pas les deux ensemble, j' ai un problème de synthaxe d'après mon mysql_error.

Aprés recherche du bouiboui, le AND pose problème. Si je met ce AND directement dans la requête, ca marche:

SELECT DISTINCT id, titre, cp FROM ann WHERE $mots AND $rcp ORDER BY id DESC


Bien sur je veux faire en sorte de le mettre dans la variable:

$rcp= $_POST['cp'];
   if(isset($_POST['cp'])&&$_POST['cp'] !== '')
	{
   $rcp = 'cp='.$rcp.'';
	}
	elseif(isset($_POST['cp'])&&$_POST['cp'] !== ''&&isset($mots)&&$mots != '')
	{
   $rcp = 'AND cp= '.$rcp.'';
	}
	else
	{
	$rcp == '';
	}


Problème, ca foire tout! Pourquoi? Et surtout comment remédier au truc???

Merci d'avance!

22 réponses

  1. Bonsoir,

    Il serai bien que tu t'inscrives sur le site CCM, c'est simple gratuit et sans engagement, on pourrait communiquer en MP
    1. Ca serait vraiment genial de ta part, et puis je pense que ca servira a d'autres, parce qu' au final, un formulaire de criteres pour moteur/annonces, je n' en ai trouvé aucun.

      Donc en fait il n' y a que ces champs la:

      mots clés, code postal, prix minimum, prix maximum.

      Merci encore pour ton devouement!
      1. donc deux champs optionnels supplémentaires.

        La les conditions if se compliquent, puisqu'il y a beaucoup de combinaisons, d'où l'intérêt de la solution de l'array comme je t'avait proposé au début.

        Pour le moment je n'ai pas trop le temps mais si je peux je te ferai ça
        1. Effectivement, merci mille fois Alain pour tout ce temps passé à m' aider, c'est tout bonnement incroyable de ta part.

          Un million de mercis!

          Je ne voudrai pas abuser....ho et puis si! J' ose! J' ai une derniere question:

          Si je voulais rajouter un champs prix minimum et prix maximum, comment faire cela?

          $req = "SELECT DISTINCT * FROM bernay_ann";
          if(isset($_POST['cp']) && !empty($_POST['cp']))
          {
          	$rcp = $_POST['cp'];
          	$req .= " WHERE cp='".$rcp."'";
          	if(isset($_POST['search']) && !empty($_POST['search'])) 
          
          {
          		$mots = $_POST['search'];
          		$req .= " AND titre='".$mots."'";
          }
          } 
          
          elseif(isset($_POST['search']) && !empty($_POST['search']))
          
           {
          	$mots = $_POST['search'];
          	$req .= " WHERE titre='".$mots."'";
          }
          $req .= " ORDER BY id DESC";
          $query = mysql_query($req)or die(mysql_error());
          $nbre = mysql_num_rows($query);
          
          if($nbre != 0)
          {
          while ($ann= mysql_fetch_array($query))
          {
          


          Merci encore!!
          1. j'ai fais une base bidon et cherché pourquoi, c'est tout con !

            tu ne peux pas mettre or die (mysql_error)) pour mysql_num_rows

            il semble que dans le cas ou aucun résultat le die s'execute donc sortie du script !!

            il faut simplement:

            $nbre = mysql_num_rows($query);
            1. Non Graffx, rien de conflictuel.

              Mon pauvre Alain, ca ne change rien du tout, j' ai meme essayé ca il y a pas 2h :/

              A quoi cela pourrai etre du en php une page blanche uniquement dans un de deux cas d' une condition???
              1. et si au lieu de :
                if($nbre != 0)

                tu mets:
                if($nbre > 0)


                on ne sait jamais ?
                1. Contributeur
                  Apparement tu as des includes, tu n'aurais pas un conflit avec une autre variable similaire? Enfin y' a pas de raison mais bon!
                  1. Je n' ai toujours pas trouvé pourquoi j' ai une page blanche si aucun résultat:

                    <?php
                    session_cache_limiter('private_no_expire, must-revalidate');
                    ?><table width="950" border="0" align="center" cellpadding="0" cellspacing="0">
                      <tr>
                        <td width="1286" height="209"><table width="950" border="0" align="center" cellpadding="0" cellspacing="0">
                            <tr>
                              <td width="710" align="center" valign="top"><br />
                    
                    
                    
                    <?php
                    
                    
                    
                    
                    $req = "SELECT DISTINCT * FROM bernay_ann";
                    if(isset($_POST['cp']) && !empty($_POST['cp'])) {
                    	$rcp = $_POST['cp'];
                    	$req .= " WHERE cp='".$rcp."'";
                    	if(isset($_POST['search']) && !empty($_POST['search'])) {
                    		$array_mots = explode(' ',$_POST['search']); //on sépare les mots
                    		$req .= " AND titre LIKE '%".implode($array_mots,"%' OR  titre LIKE '% ")."%'";
                    	}
                    } elseif(isset($_POST['search']) && !empty($_POST['search'])) {
                    	$array_mots = explode(' ',$_POST['search']); //on sépare les mots
                    	$req .= " WHERE titre LIKE '%".implode($array_mots,"%' OR  titre LIKE '% ")."%'";
                    }
                    $req .= " ORDER BY id DESC";
                    $query = mysql_query($req)or die(mysql_error());
                    $nbre = mysql_num_rows($query)or die(mysql_error());
                    
                    if($nbre != 0)
                    {
                    while ($ann= mysql_fetch_array($query))
                    {
                    
                    
                    
                    
                    ?>
                    
                    <table width="690" border="0" align="center" cellpadding="0" cellspacing="0">
                                  <tr>
                                    <td style="background:url(images/divers/bg_ann.gif);">
                    <table width="690" height="90" border="0" cellspacing="0" cellpadding="0">
                      <tr>
                        <td width="96" align="center" valign="middle"><img src="images/shops/<?php echo $ann['photo1']; ?>" alt="" width="80" height="70" /></td>
                        <td width="594" align="left" valign="top"><table width="585" border="0" align="right" cellpadding="0" cellspacing="0">
                          <tr>
                            <td height="10" colspan="2"></td>
                          </tr>
                          <tr>
                            <td width="402" height="19" style="font-weight:bolder; font-size:14px; color:#300;"><a href="index.php?a=ann&amp;id=<?php echo $ann['id']; ?>=&amp;t=<?php echo $_GET['t']; ?>&amp;cp=<?php echo $_GET['cp']; ?>&amp;v=<?php echo $_GET['v']; ?>&amp;pmn=<?php echo $_GET['pmn']; ?>&amp;pmx=<?php echo $_GET['pmx']; ?>">
                              <?php
                    		echo $ann['titre'];	
                    		?>
                            </a></td>
                            <td width="183" align="right"  style="font-weight:bolder; font-size:14px; color:#300;"><table width="170" border="0" align="right" cellpadding="0" cellspacing="0">
                              <tr>
                                <td align="right" valign="top"><a href="index.php?a=cpte&amp;pr=<?php echo $ann['vendeur']; ?>" title="Ceci est la note globale du vendeur donnée par les acheteurs. Vous pouvez consulter son profil pour plus d' informations">
                                  <?php
                    							  if($ann['pro'] == '1')
                    							  {
                    								  ?>
                                  <?php
                    								  $vendeuru = $ann['vendeur'];
                    								  
                    								  $prou2 = mysql_query('SELECT pseudo FROM bernay_users WHERE pseudo = "'.$vendeuru.'"');
                    								  $prou= mysql_fetch_array($prou2)
                    								  ?>
                                  <?php
                    								  
                    							  echo '<a href="index.php?a=cpte&id='.$prou['pseudo'].'"><img src="images/divers/pro.png" title="'.$prou['pseudo'].'" alt="" border="0" align="absbottom" /></a><img src="images/header/blank.gif" alt="" width="20" />';
                    							  }					  
                    							  ?>
                                  <?php
                    						
                    						$annvendeur = $ann['vendeur'];
                    						
                    						$retour_app2=mysql_query("SELECT COUNT(*) AS id FROM bernay_app WHERE cible = '".$annvendeur."' "); //Nous récupérons le contenu de la requête dans $retour_total
                    						$donnees_app2=mysql_fetch_assoc($retour_app2); //On range retour sous la forme d'un tableau.
                    						$app2=$donnees_app2['id']; //On récupère le total pour le placer dans la variable $total.
                    						?>
                                  <?php
                                    		$req_app2="SELECT SUM(note) as total FROM bernay_app WHERE cible = '".$annvendeur."'";
                     					    $result1_app2=mysql_query($req_app2);
                    						$val1_app2=mysql_fetch_array($result1_app2);
                    						$total_app2 = $val1_app2['total'];
                    						
                    						if($app2 > '0')
                    						{
                    						$total_app3 = ($total_app2 / $app2);
                    						}
                    						?>
                                  <?php
                    						if ($app2 == '0')
                    						{
                    						echo '0 ';
                    						}
                    						else
                    						{
                    						echo $total_app3;
                    						echo ' ';
                    						}
                    						?>
                                  / 10</a></td>
                                <td width="20">&nbsp;</td>
                              </tr>
                            </table></td>
                          </tr>
                          <tr>
                            <td height="50" align="left" valign="bottom" style="font-weight:bolder; font-size:14px; color:#300;"><?php
                    		echo $ann['cp'];
                    		echo ' ';
                    		echo $ann['ville'];
                    		?></td>
                            <td align="left" valign="bottom"><table width="100" border="0" align="right" cellpadding="0" cellspacing="0">
                              <tr>
                                <td align="right" valign="top" style="font-weight:bolder; font-size:14px; color:#300;"><?php
                                                echo $ann['prix'];
                    							?>
                                  &#x20AC;</td>
                                <td width="20" align="right" valign="top" style="font-weight:bolder; font-size:14px; color:#300;">&nbsp;</td>
                              </tr>
                            </table></td>
                          </tr>
                        </table></td>
                      </tr>
                    </table>
                    </td>
                    </tr>
                    </table>
                    <?php
                    }
                    }
                    else
                    {
                    echo '<table width="550" border="0" cellspacing="0" cellpadding="0">
                      <tr>
                        <td colspan="2" align="center" valign="top" style="font-size:14px; font-weight:bolder; text-align:center;">Aucun résultat pour cette recherche, recommencez !<br /><br />
                        <img src="images/divers/bureaucrate.png" width="500" height="402" /><br /><br /></td>
                      </tr>
                      <tr>
                        <td width="50%" align="center" valign="top">
                        <script type="text/javascript"><!--
                    google_ad_client = "ca-pub-2988340172457918";
                    /* 336x280, date de création 05/12/09 */
                    google_ad_slot = "9129849470";
                    google_ad_width = 336;
                    google_ad_height = 280;
                    //-->
                          </script>
                                <script type="text/javascript"
                    src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
                          </script></td>
                        <td height="20" align="center" valign="top">
                        <script type="text/javascript"><!--
                    google_ad_client = "ca-pub-2988340172457918";
                    /* grand carre 2 */
                    google_ad_slot = "0826716095";
                    google_ad_width = 336;
                    google_ad_height = 280;
                    //-->
                          </script>
                                <script type="text/javascript"
                    src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
                          </script>   
                          </td>
                      </tr>
                    </table>
                    ';
                    }
                    ?>
                    
                    </td>
                              <td width="240" height="547" align="left" valign="top"><span style="z-index:100;">
                                
                              </span><br />
                                <table width="230" height="203" border="0" align="right" cellpadding="0" cellspacing="0">
                                  <tr>
                                    <td height="230" align="left" valign="top">
                    				<?php 
                    				include ('crit.php');
                    				?>
                    				</td>
                                  </tr>
                              </table></td>
                            </tr>
                          </table></td>
                      </tr>
                    </table>
                    
                    1. Wow bravo et merci!! Simple et trés fonctionnel!

                      Par contre j' ai une page blanche quand il n' y a aucune résultat au lieu de mon message "pas de résultat".

                      Juste fait ca:

                      if($nbre != 0)
                      {
                      while ($ann= mysql_fetch_array($query))
                      {

                      }
                      }
                      else
                      {
                      echo 'Pas de résultat';
                      }

                      Comment cela se fait il?

                      Merci encore!!
                      1. pour plusieurs mots essayes comme ça:

                        $req = "SELECT DISTINCT * FROM bernay_ann";
                        if(isset($_POST['cp']) && !empty($_POST['cp'])) {
                        	$rcp = $_POST['cp'];
                        	$req .= " WHERE cp='".$rcp."'";
                        	if(isset($_POST['search']) && !empty($_POST['search'])) {
                        		$array_mots = explode(' ',$_POST['search']); //on sépare les mots
                        		$req .= " AND titre LIKE '%".implode($array_mots,"%' OR  titre LIKE '% ")."%'";
                        	}
                        } elseif(isset($_POST['search']) && !empty($_POST['search'])) {
                        	$array_mots = explode(' ',$_POST['search']); //on sépare les mots
                        	$req .= " WHERE titre LIKE '%".implode($array_mots,"%' OR  titre LIKE '% ")."%'";
                        }
                        $req .= " ORDER BY id DESC";
                        $query = mysql_query($req)or die(mysql_error());
                        $nbre = mysql_num_rows($query)or die(mysql_error());
                        
                        if($nbre != 0)
                        {
                        while ($ann= mysql_fetch_array($query))
                        {
                        1. Merci!

                          Alors voila, j' avais fait une erreur (pfiou!)

                          $req = "SELECT DISTINCT * FROM bernay_ann";
                          if(isset($_POST['cp']) && !empty($_POST['cp'])) {
                          	$rcp = $_POST['cp'];
                          	$req .= " WHERE cp='".$rcp."'";
                          	if(isset($_POST['search']) && !empty($_POST['search'])) {
                          		$mots = $_POST['search'];
                          		$req .= " AND titre LIKE '%".$mots."%'";
                          	}
                          } elseif(isset($_POST['search']) && !empty($_POST['search'])) {
                          	$mots = $_POST['search'];
                          	$req .= " WHERE titre LIKE '%".$mots."%' ";
                          }
                          $req .= " ORDER BY id DESC";
                          $query = mysql_query($req)or die(mysql_error());
                          $nbre = mysql_num_rows($query)or die(mysql_error());
                          
                          if($nbre != 0)
                          {
                          while ($ann= mysql_fetch_array($query))
                          {


                          Probleme encore, plusieurs mots ou mots coupés separés d' un espace et ca ne fonctionne plus.

                          Pour "lot de serviettes"

                          Si je met "lo serviett"

                          Il ne trouve plus car plusieurs mots!
                          1. Contributeur
                            J'essaie aussi en meme temps, les array c'est pas forcement mon truc non plus, en fait c'est pas si compliqué, inscrit toi et copie moi ta page en mp!
                            1. il manque une )

                              if(isset($_POST['search']) && !empty($_POST['search']))$array_recherche[]= " titre=".mysql_real_escape_string($_POST['search']); 
                              1. Contributeur
                                Pour ta methode alain il me dit:

                                Parse error: syntax error, unexpected T_VARIABLE in

                                la ligne 17 est la deuxieme de ces deux ci:

                                if(isset($_POST['cp'])&& !empty($_POST['cp'])) $array_recherche[]= " cp=".mysql_real_escape_string($_POST['cp']);
                                if(isset($_POST['search']) && !empty($_POST['search']) $array_recherche[]= " titre=".mysql_real_escape_string($_POST['search']);
                                1. Alors j' ai modifié ce que tu m' a mis, ca fonctionne avec une partie des mots, seulement si je valide le formulaire sans autre critere. Si je met le cod epostal seul ca marche aussi. Une partie des mots + CP, marche plus alors que titre complet d' une annonce + CP ca marche.

                                  Ca devient dur a comprendre. :s
                                  1. l'avantage de la solution avec un array c'est qu'elle fonctionne avec plusieurs critères, sans être obligé de passer par une ribanbelle de if

                                    pour ton pb de mots à la place de:
                                    $mots = $_POST['search'];
                                    $req .= " WHERE titre='".$mots."'";


                                    il faut mettre:
                                    $mots = $_POST['search'];
                                    	$req .= " WHERE titre LIKE '%".$mots."%' ";
                                    1. Merci a vous deux pour votre réponse, je vais pour l' instant me baser sur celui de RedloG ca ril parait moins compliqué car pas de array.

                                      Ca a l' air de fonctionner a deux détails prés : page blanche si pas de résultat, et il ne prend en compte que les phrases complètes, par exemple si un titre se nomme "lot de vélos", si je tape juste "lot", il ne trouve rien.

                                      Voici ce que j' ai fait, a savoir que je n' ai plus d'erreur, juste le probleme de groupe de mots et page blanche si pas de résultat!

                                      <?php
                                      
                                      
                                      $req = "SELECT DISTINCT id,titre,cp FROM bernay_ann";
                                      if(isset($_POST['cp']) && !empty($_POST['cp'])) {
                                      	$rcp = $_POST['cp'];
                                      	$req .= " WHERE cp='".$rcp."'";
                                      	if(isset($_POST['search']) && !empty($_POST['search'])) {
                                      		$mots = $_POST['search'];
                                      		$req .= " AND titre='".$mots."'";
                                      	}
                                      } elseif(isset($_POST['search']) && !empty($_POST['search'])) {
                                      	$mots = $_POST['search'];
                                      	$req .= " WHERE titre='".$mots."'";
                                      }
                                      $req .= " ORDER BY id DESC";
                                      $query = mysql_query($req)or die(mysql_error());
                                      $nbre = mysql_num_rows($query)or die(mysql_error());
                                      
                                      if($nbre != 0)
                                      {
                                      while ($ann= mysql_fetch_array($query))
                                      {
                                      
                                      echo $ann['titre'];
                                      echo $ann['cp'];
                                      
                                      }
                                      }
                                      else
                                      {
                                      echo 'Pas de résultat!';
                                      }
                                      ?>


                                      Merci en tout cas de vous impliquer a ce point!!!
                                      1. une variante:
                                        <?php 
                                        $array_recherche=array(); 
                                        $req="SELECT DISTINCT id,titre,cp FROM ann "; 
                                        
                                        if(isset($_POST['cp'])&& !empty($_POST['cp'])) $array_recherche[]= " cp=".mysql_real_escape_string($_POST['cp']); 
                                        if(isset($_POST['mots']) && !empty($_POST['mots']) $array_recherche[]= " mots=".mysql_real_escape_string($_POST['mots']); 
                                        
                                        if(sizeof($array_recherche) >0){ 
                                         //au moins un des criteres rempli 
                                         $conditions= "WHERE "; 
                                         $conditions.=implode($array_recherche," AND "); 
                                         $req.=$conditions." ORDER BY id DESC "; 
                                        
                                        }else{ 
                                         echo 'vous devez rentrer au moins un critere !'; 
                                        } 
                                        
                                        ?>
                                        • 1
                                        • 2