Jump to content

[Resolvido] You have an error in your SQL syntax; check the manual...


PF2G

Recommended Posts

Boas eu estou a tentar um sistema de paginação mas dá-me este erro:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-8, 8' at line 1

O que significa este erro, eu ja verifiquei todas as queries e ta tudo bem:

<?php
if($page == "all"){
$page_number = 1;
// how many records per page
$size = 8;

// we get the current page from $_GET
if (isset($_GET['page'])){
 $page_number = (int) $_GET['page'];
}
/**************************************************/
$result_images=mysql_query("SELECT * FROM  album_lang WHERE lang='".$current_lang."'");
$row_images=mysql_fetch_assoc($result_images);

$result_content=mysql_query("SELECT * FROM album_images_lang WHERE lang='".$current_lang."' AND visivel=1 ");
$total_records = mysql_num_rows($result_content);

$result_imagens=mysql_query("SELECT * FROM album_images WHERE id='".$total_records['id_image']."' AND visivel=1");
$total_imagens=mysql_fetch_assoc($result_imagens);
/**************************************************/

// create the pagination class
$pagination = new Pagination();
$pagination->setLink($current_lang."/gallery/all?page=%s");
$pagination->setPage($page_number);
$pagination->setSize($size);
$pagination->setTotalRecords($total_records);
/**************************************************/
$result_content=mysql_query("SELECT * FROM album_lang WHERE lang='$current_lang' AND visivel=1 " . $pagination->getLimitSql());
/**************************************************/

$navigation = $pagination->create_links();
}else{
/**************************************************/
if(isset($clean_url[3]) && $clean_url != ""){
 $product = $clean_url[3];
 $result_content=mysql_query("SELECT * FROM album_lang WHERE titulo='".$clean_url[2]."' AND lang='$current_lang' AND visivel=1");
}else{
/**************************************************/
 $page_number = 1;

 // how many records per page
 $size = 8;

 // we get the current page from $_GET
 if (isset($_GET['page'])){
  $page_number = (int) $_GET['page'];
 }


/**************************************************/ 
 $result_content=mysql_query("SELECT * FROM album_images WHERE visivel=1");
 $total_records = mysql_num_rows($result_content);
/**************************************************/
 // create the pagination class
 $pagination = new Pagination();
 $pagination->setLink($current_lang."/gallery/all?page=%s");
 $pagination->setPage($page_number);
 $pagination->setSize($size);
 $pagination->setTotalRecords($total_records);
/**************************************************/ 
 $result_content=mysql_query("SELECT * FROM album WHERE id='".$tax_id."' AND lang='$current_lang' AND visivel=1 " . $pagination->getLimitSql());
/**************************************************/
 $navigation = $pagination->create_links();

}
}

$num_rows_content = mysql_num_rows($result_content);
$conta_rows_content = 1;
$content = "";
if($num_rows_content > 0 || $page == "all"){
echo '<div class="content" id="page">
 <div class="container">
  <div class="interior_page" style="border-bottom:0px;">';
   if($page == "all"){
    $pageTitle="GALERIA";
   }else{
    if(isset($clean_url[3]) && $clean_url != ""){
	 $pageTitle = $row_content->titulo;
    }else{
	 $result_tax_titulo = mysql_query("SELECT * FROM album_images WHERE visivel=1 LIMIT 0,1");
	 $row_tax_titulo = mysql_fetch_object($result_tax_titulo);
	 $row_titulo=mysql_fetch_assoc($result_tax_titulo);

	 $pageTitle = $row_tax_titulo->title;
    }
   }

   echo '<div id="menu_produtos">';

   echo '</div>';

   if($num_rows_content > 1 || !isset($clean_url[3])){

    //Se existir mais que um produto apresenta a listagem de todos os existentes

    echo '<div id="products">';
	 echo "<h1 class='title'>".$pageTitle."</h1>";

	 echo '<div class="produts_list">';
	 $count_products = 1;


   //////////   IMAGENS TODAS   ////////////
	 /***************************/

    if($clean_url[2]='all')
    {
	  $inicio = ($size * $page) - $size;
		 //Monta o SQL com LIMIT para exibição dos dados 
	  $sql = "SELECT * FROM album_images ORDER BY id ASC LIMIT $inicio, $size";
	  $qr  = mysql_query($sql) or die(mysql_error());

	  while($ln = mysql_fetch_assoc($qr)){
	  echo 'IMAGEM :'.$ln['produto'].'<br /> <hr />';
	  }
	  // SEGUNDA PARTE DA PAGINAÇÃO

	  //SQL para saber o total
	  $sqlTotal   = "SELECT id FROM album_images";
	  $qrTotal    = mysql_query($sqlTotal) or die(mysql_error());
	  $numTotal   = mysql_num_rows($qrTotal);

	  //O calculo do Total de página ser exibido
	  $totalPagina= ceil($numTotal/$size);
	 }
	 /***************************/

	 /* Paginação */
	 echo '<div class="clearfloat"></div>';
	 echo $navigation; // will draw our page navigation
	 echo '<div class="clearfloat"></div>';
	 echo '</div>';

    echo '</div>';

   }

   echo '<div class="clearfloat"></div>';
  echo  '</div>
   <div class="clearfloat"></div>';
echo  '</div>
 </div>';

}else{
header("Status: 404 Not Found");
header( "Location: ".$url."/".$current_lang."/pages/error/404" );
die();
}
?>

Alguem me pode ajudar?

Obrigado,

PF2G

Link to comment
Share on other sites

tenho a sensação que

$pagination->getLimitSql()

só te retorna o -8, 8

deverás adicionar a palavra reservada " LIMIT "antes de concatenares o resultado da chamada dessa função

isto tudo é supor porque não faço ideia que raio de classe é essa de paginação ...

PS : já agora ... sabes que o início ser -8 não faz sentido

Edited by HappyHippyHippo
IRC : sim, é algo que ainda existe >> #p@p
Link to comment
Share on other sites

tenho a sensação que

$pagination->getLimitSql()

só te retorna o -8, 8

deverás adicionar a palavra reservada " LIMIT "antes de concatenares o resultado da chamada dessa função

isto tudo é supor porque não faço ideia que raio de classe é essa de paginação ...

PS : já agora ... sabes que o início ser -8 não faz sentido

Esta é a classe:

<?php
class Pagination
{
/**
 * Current Page
 *
 * @var integer
 */
var $page;

/**
 * Size of the records per page
 *
 * @var integer
 */
var $size;

/**
 * Total records
 *
 * @var integer
 */
var $total_records;

/**
 * Link used to build navigation
 *
 * @var string
 */
var $link;

/**
 * Class Constructor
 *
 * @param integer $page
 * @param integer $size
 * @param integer $total_records
 */
function Pagination($page = null, $size = null, $total_records = null)
{
 $this->page = $page;
 $this->size = $size;
 $this->total_records = $total_records;
}

/**
 * Set's the current page
 *
 * @param unknown_type $page
 */
function setPage($page)
{
 $this->page = 0+$page;
}

/**
 * Set's the records per page
 *
 * @param integer $size
 */
function setSize($size)
{
 $this->size = 0+$size;
}

/**
 * Set's total records
 *
 * @param integer $total
 */
function setTotalRecords($total)
{
 $this->total_records = 0+$total;
}

/**
 * Sets the link url for navigation pages
 *
 * @param string $url
 */
function setLink($url)
{
 $this->link = $url;
}

/**
 * Returns the LIMIT sql statement
 *
 * @return string
 */
function getLimitSql()
{
 $sql = "LIMIT " . $this->getLimit();
 return $sql;
}

/**
 * Get the LIMIT statment
 *
 * @return string
 */
function getLimit()
{
 if ($this->total_records == 0)
 {
  $lastpage = 0;
 }
 else
 {
  $lastpage = ceil($this->total_records/$this->size);
 }

 $page = $this->page; 

 if ($this->page < 1)
 {
  $page = 1;
 }
 else if ($this->page > $lastpage && $lastpage > 0)
 {
  $page = $lastpage;
 }
 else
 {
  $page = $this->page;
 }

 $sql = ($page - 1) * $this->size . "," . $this->size;

 return $sql;
}

/**
 * Creates page navigation links
 *
 * @return  string
 */
function create_links()
{
 $totalItems = $this->total_records;
 $perPage = $this->size;
 $currentPage = $this->page;
 $link = $this->link;

 $totalPages = floor($totalItems / $perPage);
 $totalPages += ($totalItems % $perPage != 0) ? 1 : 0;
 if ($totalPages < 1 || $totalPages == 1){
  return null;
 }
 $output = null;
 //$output = '<span id="total_page">Page (' . $currentPage . '/' . $totalPages . ')</span> ';

 $loopStart = 1;
 $loopEnd = $totalPages;
 if ($totalPages > 5)
 {
  if ($currentPage <= 3)
  {
   $loopStart = 1;
   $loopEnd = 5;
  }
  else if ($currentPage >= $totalPages - 2)
  {
   $loopStart = $totalPages - 4;
   $loopEnd = $totalPages;
  }
  else
  {
   $loopStart = $currentPage - 2;
   $loopEnd = $currentPage + 2;
  }
 }
 if ($loopStart != 1){
  $output .= sprintf('<li class="disabledpage"><a href="' . $link . '">«</a></li>', '1');
 }

 if ($currentPage > 1){
  $output .= sprintf('<li class="nextpage"><a href="' . $link . '">< Anterior</a></li>', $currentPage - 1);
 }

 for ($i = $loopStart; $i <= $loopEnd; $i++)
 {
  if ($i == $currentPage){
   $output .= '<li class="currentpage">' . $i . '</li> ';
  } else {
   $output .= sprintf('<li><a href="' . $link . '">', $i) . $i . '</a></li> ';
  }
 }
 if ($currentPage < $totalPages){
  $output .= sprintf('<li class="nextpage"><a href="' . $link . '">Seguinte ></a></li>', $currentPage + 1);
 }

 if ($loopEnd != $totalPages){
  $output .= sprintf('<li class="nextpage"><a href="' . $link . '">»</a></li>', $totalPages);
 }
 return '<div class="pagination"><div class="num_rows">Foram encontrados '.$totalItems.' registo(s).</div><ul>' . $output . '</ul></div>';
}
}
?>
Link to comment
Share on other sites

se a classe coloca o " LIMIT " então verifica melhor porque razão o limite inferior é negativo

O problema esta neste cálculo:

$inicio = ($size * $page)-$size;

Pq desta maneira ele funciona, mas se eu mudar de página continua com as mesmas imagens não muda:

if($clean_url[2]='all')
       {
         $inicio = ($size * $page);
            //Monta o SQL com LIMIT para exibição dos dados 
         $sql = "SELECT * FROM album_images ORDER BY id ASC LIMIT $inicio, $size";
         $qr  = mysql_query($sql) or die(mysql_error());

         while($ln = mysql_fetch_assoc($qr)){
         echo 'IMAGEM: '.$ln['imagem'].' -> '.$ln['id'].'<br /> <hr />';
         }
         // SEGUNDA PARTE DA PAGINAÇÃO

         //SQL para saber o total
         $sqlTotal   = "SELECT id FROM album_images";
         $qrTotal    = mysql_query($sqlTotal) or die(mysql_error());
         $numTotal   = mysql_num_rows($qrTotal);

         //O calculo do Total de página ser exibido
         $totalPagina= ceil($numTotal/$size);

Por exemplo como o $size=8 ele só apresenta as 8 imagens em todas as páginas.


Alguem me pode dizer o que é que esta mal com este codigo, pq so me mostra as primeiras 8 imagens, em todas as paginas:

       if($clean_url[2]='all')
       {

            //Monta o SQL com LIMIT para exibição dos dados 
         $sql = "SELECT * FROM album_images ORDER BY id ASC LIMIT 0, $size";
         $qr  = mysql_query($sql) or die(mysql_error());

       ?>
       <table>
       <?php
         $i=0;
         while($ln = mysql_fetch_assoc($qr)){
        if ($i==0)
        {
         echo '<tr>';
        }
       ?>
        <td>
        <table><tr><td><a href=""><img src="<?php echo $ln['imagem']; ?>" width="150px" height="150px"></a></td></tr>
        <tr><td align="center"><?php echo $ln['id']; ?></td></tr></table>
        </td>
       <?php
        $i=$i+1;
        if ($i==4)
        {
         $i=0;
        }
         }
         ?>

         </table>

         <?php
         }
        /***************************/

        /* Paginação */
        echo '<div class="clearfloat"></div>';
        echo $navigation; // will draw our page navigation
        echo '<div class="clearfloat"></div>';
        echo '</div>';

       echo '</div>';
Edited by brunoais
2x post junto
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.