Switch Result

Asked

Viewed 247 times

-5

<?php
include("conectar.php");

$quantidade = 1;
$pagina = (isset($_GET ['pagina'])) ? (int) $_GET['pagina'] : 1;
$inicio = ($quantidade * $pagina) - $quantidade;
$where = "";
$estado = '' . @$_POST['estado'];
$distrito = '' . @$_POST['distrito'];
$concelho = '' . @$_POST['concelho'];

switch ([$estado, $distrito, $concelho]) {

    Case ['Indiferente', 'Indiferente', 'Indiferente']:
        break;
    case ['Indiferente', 'Aveiro', 'Indiferete']:
        $where = "WHERE tb_trabalhador.Distrito = 'Aveiro' ";
        break;
    case ['Indiferente', 'Aveiro', 'Agueda']:
        $where = "WHERE tb_trabalhador.distrito = 'Aveiro' AND tb_trabalhador.concelho = 'Agueda'";
        break;
}


//Aqui tenho a dúvida pois nem sempre quero utilizar $SQL. Se for ['autorizado','Indiferente','Indiferente'] Já tem uma query diferente. Como posso fazer essa distinção? 


$sql = "select * from tb_detalhe_trabalhador inner join tb_trabalhador on tb_detalhe_trabalhador.id = tb_trabalhador.id inner join tb_equipamentos on tb_detalhe_trabalhador.id = tb_equipamentos.id $where order by tb_trabalhador.id asc LIMIT $inicio, $quantidade";
$qr = mysql_query($sql) or die(mysql_error());
while ($exibe = mysql_fetch_array($qr)) {
    echo "<table>";

    echo "<tr><td>Nome:</td>";
    echo "<td>" . $exibe["Nome"] . "</td></tr>";

    echo "</table>";
}

$sqltotal = "SELECT id FROM tb_trabalhador $where";
$qrtotal = mysql_query($sqltotal) or die(mysql_error());
$numtotal = mysql_num_rows($qrtotal);
$totalpagina = ceil($numtotal / $quantidade);

echo '<a href="?pagina=1">Primeira página</a>';

for ($i = 1; $i <= $totalpagina; $i++) {
    if ($i == $pagina)
        echo $i;
    else
        echo"<a href=\"?pagina=$i\">$i</a>";
}

echo '<a href="?pagina=$totalpagina">Ultima Pagina</a>';
?>
  • Could you post the whole code? or are you sure it’s in this snippet that’s giving the problem??

  • The problem is in this line $qr = mysql_query($sql) or die(mysql_error()); or after using any case gives me the problem.

  • Is any case giving error? Variables $sqland $qr exist outside the cases?

  • line before While. Any case gives the same error

  • Before the switch trial var $sql, $qr;

  • With var before Switch not even show me page only error..

Show 1 more comment

3 answers

3

I answered here what I had already put in a double question, and deleted from there.

Well, what I notice (looking a little fast) is that when a person changes pages, there are no more variables of $_POST, so the query cannot run.

Or you change your POST for GET and includes in the links the query data, or uses POST to change page too, or you will need to rethink this logic, either using session variables or some other technique to preserve the results.

Here’s a possible alternative, using POST for everything. Note at the very end, in the pagination part, how the fields of the original form were passed along with the desired page:

<?php
include("conectar.php");

$quantidade = 1;
$pagina = (isset($_POST['pagina'])) ? (int)$_POST['pagina'] : 1;
$inicio = $quantidade * $pagina - $quantidade;

$where = "";
$estado = ''.@$_POST['estado'];
$distrito = ''.@$_POST['distrito'];
$concelho = ''.@$_POST['concelho'];

switch([$estado, $distrito, $concelho])
{
   case ['Indiferente','Aveiro','Indiferente']:
      $where= "Where tb_trabalhador.Distrito = 'Aveiro'";
      break;

  case ['Indiferente','Aveiro','Agueda']:
      $where= "WHERE tb_trabalhador.Distrito = 'Aveiro' AND 
         tb_trabalhador.Concelho = 'Agueda'";
      break;
}

$sql = "select * from tb_detalhe_trabalhador inner join tb_trabalhador on   tb_detalhe_trabalhador.id = tb_trabalhador.id inner join tb_equipamentos on tb_detalhe_trabalhador.id = tb_equipamentos.id $where ORDER BY tb_trabalhador.id asc LIMIT $inicio, $quantidade";

$qr = mysql_query($sql) or die(mysql_error());

while($exibe = mysql_fetch_array($qr)){
   echo "<table>"; 
   echo  "<tr><td>Nome:</td>";
   echo "<td>".$exibe["Nome"]."</td></tr>";
} 

$sqltotal = "SELECT id FROM tb_trabalhador";
$qrtotal = mysql_query($sqltotal) or die(mysql_error());
$numtotal = mysql_num_rows($qrtotal);
$totalpagina = ceil ($numtotal/$quantidade);

echo '<form>';
echo '<input type="hidden" name="estado" value="'.htmlentities($estado).'">';
echo '<input type="hidden" name="distrito" value="'.htmlentities($distrito).'">';
echo '<input type="hidden" name="concelho" value="'.htmlentities($concelho).'">';
for ($i = 1; $i <= $totalpagina; $i++){
   if($i == $pagina)
      echo $i;
   else
   echo '<input type="submit" name="pagina" value="'.$i.'">';
}
echo '</form>';
?>  

Remember to adjust the source form to use it Casing of characters in the name="" inputs. I passed it all to lower case.

There are other problems, such as lack of optimization, and also in the use of insecure functions mysql_ instead of mysqli_, but a search on Sopt or on the Internet as a whole can give more details on this.

Also you could have an sql only, and include the condition WHERE of "Aveiro" as a variable. What’s more: if you use a collation case insensitive (which is usually the default), Mysql will find "Aveiro", "Aveiro", "AVEIRO" in the same way.

I imagine you’re using 1 as a test-only quantity.

Another detail: to count the records, just use SELECT COUNT(*) FROM tabela, doesn’t need mysql_num_rows.

Of curiosity, an optimization for the code, if it were to stay as it is, that would be to take the entire switch and leave only these two lines in place:

$where= $distrito=='aveiro'?" WHERE tb_trabalhador.Distrito = 'Aveiro' ":"";
$sql = "select * from tb_detalhe_trabalhador inner join tb_trabalhador on   tb_detalhe_trabalhador.id = tb_trabalhador.id inner join tb_equipamentos on tb_detalhe_trabalhador.id = tb_equipamentos.id $where ORDER BY tb_trabalhador.id asc LIMIT $inicio, $quantidade";
  • switch([$state, $district, $county]) { case ['Indifferent','Indifferent']: $Where = ""; break; Does not go to the second page. My question is whether the way I am using the Switch is the best.

  • I think you needed to master the language a little more, because it doesn’t make any sense that switch you added (for the explanations already given). The way I had proposed, the switch would be only for when it has Where.

  • It would be nice for you not to confuse things, take the switch all, leave one sql alone, and make the paging work. Without any swicth, as if everything was indifferent. AFTER it works, we take care of the switch. I’m sure it’s something you can work out in five minutes, but not from far away and trying to guess what’s going on. Try to solve one thing at a time, I’m sure it will make it easier for you.

  • I was left with a doubt only in the way you told me. is the following I have several querys depending on what the user chooses. I’m going to alter my question to see if you can explain to me briefly a way

  • @user3253195 fix the paging first would be better. The query is easy to fix. In fact you apparently need a single query, and change only Where, if I got it right the "real problem".

1


You can not put code that is not related to switch within the switch because this is bad programming practice. Another thing is to define $sql before you even enter the switch, because there is no guarantee that $sql will be set within the switch.

It’s right to use it this way:

$quantidade = 1;
$pagina = (isset($_GET ['pagina'])) ? (int)$_GET['pagina'] : 1;
$inicio = ($quantidade * $pagina) - $quantidade;
$sql = "";

if (isset($_POST['estado']) AND ($_POST['Distrito']) AND ($_POST['Concelho']))
{
    switch([$_POST['estado'] , $_POST['Distrito'], $_POST['Concelho']])
    {
        case ['Indiferente','Indiferente','Indiferente']:
            $sql = "select * from tb_detalhe_trabalhador inner join tb_trabalhador on tb_detalhe_trabalhador.id = tb_trabalhador.id inner join tb_equipamentos on tb_detalhe_trabalhador.id = tb_equipamentos.id ORDER BY tb_trabalhador.id asc LIMIT $inicio, $quantidade";
            $qr = mysql_query($sql) or die(mysql_error());
            break;
        case ['Indiferente','Aveiro','Indiferente']:
            $sql = "(Query) asc LIMIT $inicio, $quantidade";
            $qr = mysql_query($sql) or die(mysql_error());
            break;
        //(Varios cases)
    }

    $qr = mysql_query($sql) or die(mysql_error());
    while($exibe = mysql_fetch_array($qr)){
        echo "<table>"; 
        echo  "<tr><td>Nome:</td>";
        echo "<td>".$exibe["Nome"]."</td></tr>";
        //...
    }
}
  • Se eu tiro o IF da-me erros. Notice: Undefined index: estado Notice: Undefined index: Ditrito Notice: Undefined index: Concelho

  • But it’s not to take the if. I just pointed out the code that should be changed. I’ll change the answer for you.

  • And before I can put the pagination? Or I have to put it somewhere else?

  • @user3253195 Can yes.

  • But I have a problem because it only shows me the first query values. shows me id1 and id2 no longer shows.

  • @user3253195 Where are these id1 and id2? I edited the answer again.

  • id1 and id2 are in the mysql database. This will be to show the results of an options query. When I ask to show me the second page tells me Query was Empty. But if I test the code in slq it shows me the two results

  • 3

    This is a classic question from the series "developing the application via Q&A" :)

Show 3 more comments

0

I got here because of a duplicate: Switch with several POST

I’m going to share something I didn’t see in any response or comment. It is a more flexible technique that allows conditional structures:

$foo = 1;
$bar = 2;
switch(true)
{
    case ($foo > $bar):
        echo 'foo maior que bar';
    break;
    case ($foo < $bar):
        echo 'foo menor que bar';
    break;
    case ($foo == $bar):
        echo 'foo igual a bar';
    break;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.