8722 sujets

Développement web côté serveur, CMS

Bonjour à tous,

Je suis en train d'apprendre php et j'ai un projet de site associatif de petite annonce et annuaire ou je vais intégrer en plus un moteur de shopping avec l'api Kelkoo pour monétiser le tout (site à but non lucratif, plus d'info par MP)...

J'ai deux problèmes que je n'arrive pas à résoudre :

1 : je fais une recherche pour iphone par exemple, l'api me renvoi les résultats, avec la fonction de pagination j'affiche 10 résultats par page et l'URL de la première page à cette forme :
http://www.monsite.fr/test/shopping.php?q=iphone

...je passe à la page 2 et l'URL à cette forme :
http://www.monsite.fr/test/shopping.php?q=iphone&count=10&page=2

je reviens en cliquant sur le lien à la page 1 et l'URL à cette forme :
http://www.monsite.fr/test/shopping.php?q=iphone&count=10&page=1
...mais là, surprise, je n'ai plus de résultats Smiley eek

2 : j'arrive à savoir le nombre total de page en fonction du nombre de produit (nb total de produit / 10 , vu que je veux 10 produits par page), par contre je ne sais pas comment faire pour que se soit pri en compte dans la pagination (ex: préc 1 2 3 ... 629 suiv (si il y a 6290 produits renvoyés) )...

Voici mon code qui doit être nettoyé et optimisé (soyez indulgent, je débute), hésitez pas à me corriger pour me permettre de comprendre mes erreurs, merci d'avance :

Le formulaire :

<body class="thrColLiqHdr">
<div id="content">	
<form method="get" action="shopping.php" target="_self" style="background:#fefeed; padding:5px;">
<input type="text" onblur="if (this.value == '') {this.value = '  Vous recherhez : Un produit, Un marchand, ...';}" onfocus="if (this.value == '  Vous recherhez : Un produit, Un marchand, ...') {this.value = '';}" value="  Vous recherhez : Un produit, Un marchand, ..." name="q" style="width:400px; -moz-border-radius:5px 5px 5px 5px; border: 2px solid #cccccc;" />
<button type="submit" class="buttonKelkoo">&nbsp;Go >>></button>
</form>


le php :

// Numero de page (1 par défaut)
if(!empty($_GET['page']) && is_numeric($_GET['page'])){
	if ($_GET['page'] > 50){
		$page = 50;
	}
	else $page = $_GET['page'];
}
else $page = 1;

if(!empty($_GET['q'])){
	$query = $_GET['q'];

}

if(!empty($_GET['count']) && is_numeric($_GET['count'])){
	
		$nb_count = $_GET['count'];
	
}
else $nb_count = 10;

if(isset($_GET['page']) && is_numeric($_GET['page'])){
	
		$nb_start = $_GET['page'];
}
else $nb_start = 0;

if( isset($_GET['page']) )
	$nb_start = ($page-1) * $nb_count;

function pagination($current_page, $nb_pages, $link='?page=%d', $around=1, $firstlast=3)
{
	
	$pagination = '';
	$link = preg_replace('`%([^d])`', '%%$1', $link);
	if ( !preg_match('`(?<!%)%d`', $link) ) $link .= '%d';
	if ( $nb_pages > 1 ) {
		if ( $nb_pages > 50 ) {$nb_pages = 50;}
		// Lien précédent
		if ( $current_page > 1 )
			$pagination .= '<a class="prevnext" href="'.sprintf($link, $current_page-1).'" title="Page précédente">&laquo; Précédent</a>';
		else
			$pagination .= '<span class="prevnext disabled">&laquo; Pr&eacute;c&eacute;dent</span>';

		// Lien(s) début
		for ( $i=1 ; $i<=$firstlast ; $i++ ) {
			$pagination .= ' ';
			$pagination .= ($current_page==$i) ? '<span class="current">'.$i.'</span>' : '<a href="'.sprintf($link, $i).'">'.$i.'</a>';
		}

		// ... après pages début ?
		if ( ($current_page-$around) > $firstlast+1 )
			$pagination .= ' &hellip;';

		// On boucle autour de la page courante
		
		$start = ($current_page-$around)>$firstlast ? $current_page-$around : $firstlast+1;
		
		$end = ($current_page+$around)<=($nb_pages-$firstlast) ? $current_page+$around : $nb_pages-$firstlast;
		for ( $i=$start ; $i<=$end ; $i++ ) {
			$pagination .= ' ';
			if ( $i==$current_page )
				$pagination .= '<span class="current">'.$i.'</span>';
			else
				$pagination .= '<a href="'.sprintf($link, $i).'">'.$i.'</a>';
		}

		// ... avant page nb_pages ?
		if ( ($current_page+$around) < $nb_pages-$firstlast )
			$pagination .= ' &hellip;';

		// Lien(s) fin
		$start = $nb_pages-$firstlast+1;
		if( $start <= $firstlast ) $start = $firstlast+1;
		for ( $i=$start ; $i<=$nb_pages ; $i++ ) {
			$pagination .= ' ';
			$pagination .= ($current_page==$i) ? '<span class="current">'.$i.'</span>' : '<a href="'.sprintf($link, $i).'">'.$i.'</a>';
		}

		// Lien suivant
		if ( $current_page < $nb_pages )
			$pagination .= ' <a class="prevnext" href="'.sprintf($link, ($current_page+1)).'" title="Page suivante">Suivant &raquo;</a>';
		else
			$pagination .= ' <span class="prevnext disabled">Suivant &raquo;</span>';
	}
	return $pagination;
}

// MSG à afficher 
  $noresultsmessage = 'Pas de r&eacute;sultats pour cette recherche.';
  $resultsmessage = 'r&eacute;sultats $nb_start &aacute; $end sur $all pour';
  $badtermmessage = 'Recherche interdite';

function UrlSigner($urlDomain, $urlPath, $partner, $key){

	settype($urlDomain, 'String');
	settype($urlPath, 'String');
	settype($partner, 'String');
	settype($key, 'String');

	$URL_sig = "hash";
	$URL_ts = "timestamp";
	$URL_partner = "aid";
			
	$URLreturn = "";
	$URLtmp = "";
	$s = "";
	// get the timestamp
	$time = time();

	// Remplace les espaces " " par un "+"
	$urlPath = str_replace(" ", "+", $urlPath);

	// Format de l'URL
	$URLtmp = $urlPath . "&" . $URL_partner . "=" . $partner . "&" . $URL_ts . "=" . $time;
			
	// URL needed to create the tokken
	$s = $urlPath . "&" . $URL_partner . "=" . $partner . "&" . $URL_ts . "=" . $time . $key;
			
	$tokken = "";
	$tokken = base64_encode(pack('H*', md5($s)));
	$tokken = str_replace(array("+", "/", "="), array(".", "_", "-"), $tokken);

	$URLreturn = $urlDomain . $URLtmp . "&" . $URL_sig . "=" . $tokken;
			
	return $URLreturn;
}

function fitre_xml($val) {
	// Nettoyage complet des parasites [smile]	
	return utf8_decode(ereg_replace("\]\]>","",ereg_replace("<!\[CDATA\[","",$val)));
} 

// Variable indispensable :
$keypartner = "zpOgdBtu";
$idpartner  = "94756421";
$recherche  = urlencode(utf8_decode($_GET["q"]));

// Recuperer le liens de traking TRADEDOUBLER
$tradedoubler = "http://clk.tradedoubler.com/click?p=17928&a=1769862&g=1854288";
// Exemple : "http://clk.tradedoubler.com/click?p=17928&a=idtradersite&g=iddetracking&url="

// Format des données renvoyer par l'API...
if(isset($_GET['page']))
$format = '&start='.$nb_start.'&results='.$nb_count.'&show_products=1&show_subcategories=1&show_refinements=1';

else $format = '&start=1&results=15&show_products=1&show_subcategories=1&show_refinements=1';

// Signature de URL
$backendURL = UrlSigner('http://fr.shoppingapis.kelkoo.com', '/V3/productSearch?query='.$recherche.''.$format, $idpartner, $keypartner);

// Récuperation du FLUX XML
$xml = simplexml_load_file($backendURL);
$all = $xml->Products[totalResultsAvailable];

$format_url = 'shopping.php?q='.$_GET['q'].'&count='.$nb_count.'&page=%d';

//test avec ancien code version V1

	// if there are no results, display the no results message
		  if($all < 1){
			echo '<p id="resultcounter">'.$noresultsmessage.'</p>';

	// otherwise display the results message and replace the placeholders
	// with the real data
		  } else {
			$resultsmessage = str_replace('$nb_start',$nb_start+1,$resultsmessage);
			$end = $all >$nb_start+ $nb_count ? $nb_start+ $nb_count : $all;
			$resultsmessage = str_replace('$end',$end,$resultsmessage);
			$resultsmessage = str_replace('$all',$all,$resultsmessage);
			echo '<div class="div_info_src"><div>'.$resultsmessage.'<span style="font-weight: bold"> '.$_GET['q'].'</span><div id="chargement"></div></div></div>';
		  }

// Nombre d'info par page
$pagination = $nb_count;

// Numéro du 1er enregistrement à lire
$limit_start = ($page - 1) * $pagination;

// On boucle sur tous les résultats et on afficher les bonnes données
     foreach ($xml->Products->Product as $produit) {
				$dispo = $produit->Offer->Availability;
				
				echo "
				<div id=aff_Kelkoo>
    <div class=affichageK>
        <div>
            <div></div>
        </div>
    </div>
    <div class=affichageKCenterLeft>
        <div class=affichageKCenterRight>
            <div class=affichageKCenter></div>
				<div id=titre-produit>".$produit->Offer->Title." </div>\n";
				echo "<img id=image_produit alt='".$produit->Offer->Title."' title='".$produit->Offer->Title."' src=".$produit->Offer->Images->Image->Url." width=90 height=90 /><img class=logo src=".$produit->Offer->Merchant->Logo->Url." alt=".$produit->Offer->Merchant->Name." /> \n";
				echo "<div class=description>".$produit->Offer->Description." <br />\n";
				echo "<strong>Disponibilit&eacute; : \n";
				switch ($dispo)
				{
				case 1:
					echo "En stock";
					break;
				case 2:
					echo "En commande";
					break;
				case 3:
					echo "Non renseign&eacute;";
					break;
				case 4:
					echo "Pr&eacute;-commande";
					break;
				case 5:
					echo "Disponible sur commande";
					break;
				case 6:
					echo "Rupture de stock";
					break;
				}
				echo " | D&eacute;lai de livraison : ".$produit->Offer->DeliveryTime." | Frais de livraison : ".$produit->Offer->Price->DeliveryCost." &euro;</strong></div><div>&nbsp;</div>\n";
				echo "<div id=prix_lien>Prix total&nbsp;<a href=".$tradedoubler."&epi=".$recherche.",".$produit->Offer->Category[id]."&epi2=recherche-".$produit->Offer->Merchant[id]."&url=".$produit->Offer->Url."";
				echo " onClick='javascript:pageTracker._trackEvent(\"".$produit->Offer->Category->Name."\",\"Clic\", \"".$produit->Offer->Merchant->Name."\", \"\" );' target=_blank> \n";
				echo "".$produit->Offer->Price->TotalPrice." &euro;&nbsp;<img class=offre src=http://www.monsite/images/kelkoo/kelkoo_bouton_lien.png alt=Voir cette offre border=0 /></a>
				
				</div> 
				<br/>
				</div>
    </div>
    <div class=affichageKBottom>
        <div>
            <div></div>
        </div>
    </div>
	
</div>		
				\n";
				
				}
				
           echo" </div>";
	  
$xml = str_replace("/<term><!\[CDATA\[/",'<term>',$xml);
$xml = str_replace("/\]\]><\/term>/",'</term>',$xml);

// Nb d'enregistrement total
$nb_total = $all;

// Pagination
$nb_pages = ceil($nb_total / $pagination);
$nb_totalPages = ceil($nb_total / 10);
echo $nb_totalPages;
$current_page = $page;

// Affichage
echo '<p class="pagination">' . pagination($current_page, $nb_pages, $format_url) . '</p>';

Modifié par Artof43 (29 Oct 2013 - 13:31)