Pass variables by php

4

I have a .php file which is responsible for managing news on a website, I need to filter by categories if the user presses a certain option on the menu. I am sending variables by means of php to the same file to later receive the value of the variable and translate it into my SQL query.

The problem is that entering the page for the first time gives me an error, since I am trying to recover the value of a variable that does not exist yet.

Does anyone know how I can solve this?

This is how I send my variables:

<li><a href="noticias.php">Todas</a> </li>
<li><a href="noticias.php?categoria=academicas">Academicas</a></li>
<li><a href="noticias.php?categoria=deportivas">Deportivas</a></li>
<li><a href="noticias.php?categoria=otras">Otras</a></li>

And this way I receive them in the same file noticias.php :

<?php
$consulta_tabla=($_GET['categoria']);

if($consulta_tabla == "deportivas"){
    $categoria = "deportivas";
}else
    if($consulta_tabla == "academicas"){
    $categoria = "academicas";
}else
        if($consulta_tabla == "otras"){
    $categoria = "otras";
}
?>

Here is the problem, because when you load for the first time noticia.php $ consult_table has no value.

    
asked by Agustin Acosta 14.04.2016 в 23:45
source

3 answers

8

To check if a variable has some assigned value you can use isset () . I suggest that instead of nesting so many if you use a switch.

For example:

<?php
$consulta_tabla=($_GET['categoria']);
if(isset($consulta_tabla)){
  switch ($consulta_tabla) {
    case 'deportivas':
      $categoria = "deportivas";
      break;
    case 'academicas':
      $categoria = "academicas";
      break;
    case 'otras':
      $categoria = "otras";
      break;
    default:
      # code...
      break;
  }
}

?>
    
answered by 15.04.2016 в 00:00
8

You can set a default query:

$consulta_tabla = "otras";
$consulta_tabla=($_GET['categoria']);

or make a conditional that would get the same result:

if(isset($_GET['categoria']) && $_GET['categoria] != null){
    $consulta_tabla = $_GET['categoria'];
}else{
    $consulta_tabla = 'otras';
}

or the most advisable to do verifications through a switch:

switch($_GET['categoria']){
    case 'deportivas':
        $categoria = "deportivas";
    break;

    case 'academicas':
        $categoria = "academicas";
    break;

    case 'otras':
        $categoria = "otras";
    break;

    default:
        $categoria = "otras";
}
    
answered by 14.04.2016 в 23:59
0

When you use only 1 variable for a comparison it is better that you use the switch/case with this you can have greater order, the if is for multiple validations within one etc ... answering your question

if( !isset($_GET["categoria"]) ){
    $categoria = '';
}

// validacion a la DB
if( !$categoria ){
    // no agregar el SQL que contiene el campo de 'categoria'
    $sql_cate = '';
}else{
    $sql_cate = " and categoria = '$categoria' ";
}
    
answered by 29.05.2016 в 23:43