"Warning: Division by zero" in php

1

Friends I need help with a code ... I'm trying to modify a news template in php and I get this error, and I can not fix that I leave the message and the code.

  

Warning: Division by zero in ... on line 89   Something is wrong in your query syntax.

$num_news = $mysql->num_rows();
 $num_pages = ceil($num_news / $news_per_page);

 if ($_GET['page'] != 1)

thanks.

    
asked by Rodrigo Gonzalez 03.01.2017 в 19:04
source

5 answers

1

In Mathematics and therefore in computing the division between zero is not defined so you have to validate that the numerator must not be zero and I think that by logic of your program must be greater than zero.

      if ( $news_per_page > 0)
         $num_pages = ceil($num_news / $news_per_page);
    
answered by 03.01.2017 в 19:32
0

You should define by default how many results you want to see per page, that's why it's the division

$news_per_page = 10;// Número de resultados por página
$num_pages = ceil($num_news / $news_per_page);// Número de páginas
    
answered by 03.01.2017 в 19:18
0

The warning message indicates the problem:

  

Warning: Division by zero in ... on line 89 Something is wrong in your   query syntax.

variable $news_per_page has a value of zero!

You must initialize with a correct value $news_per_page since you want to obtain the number of pages according to the number of news per page.

How many news per page do you want? this value must be: $news_per_page , this variable must not have the value of 0.

    
answered by 03.01.2017 в 19:28
0

Just verify that your variable is not zero:

if ( $news_per_page != 0)
    $num_pages = ceil($num_news / $news_per_page);
else
    {
       // hacer algo diferente, poner un valor por defecto por ejemplo:
       $news_per_page = 10;
       $num_pages = ceil($num_news / $news_per_page);
    }

Being a warning does not mean that the variable is zero, but it is a possibility and therefore it is indicated that you prevent it.

    
answered by 03.01.2017 в 19:07
0

You can validate that the value of the variable $news_per_page is different from zero ( 0 ) using the ternary operator ( ?: ).

Example:

 // Si $news_per_page fuera cero (0), false o vacío (""), entonces se asignara 1 
 $var = $var ? $var : 10;
    
answered by 03.01.2017 в 20:51