Use two or more times While for the same Select?

0

I'm putting together a listing page and product output register and I'm having trouble pulling the information and doing the while a second time.

Example:

$sql_for = mysql_query ("SELECT * FROM cliente ORDER BY cli_nome ASC");
$sql_for2 = mysql_query ("SELECT * FROM cliente WHERE cli_status='on');

Here shows the list in a table:

while($linha_for = mysql_fetch_object($sql_for)){
    echo $linha_for->cli_nome;
}

Here it would be to show within a select option with all clients

while($linha_for = mysql_fetch_object($sql_for)){
   echo $linha_for->cli_nome;
}

This would be to display within a select option and here only active clients

while($linha_for2 = mysql_fetch_object($sql_for2)){
   echo $linha_for2->cli_nome;
}

Now the problem is: the idea was to do another while by taking advantage of the existing query and pulling the client data by id , but could not find a schema to make a function. It repeats the data obtained in the first query . I was unable to filter the information.

Here is the code I found:

function listarTodosClientes($db){
   $sql = 'select * from cliente';
   $res = mysql_query($sql) or die(mysql_error());

   $lista = array();
   while($item = mysql_fetch_assoc($res)){
      $lista[] = $item;
   }

  return $lista;
}

To use:

//$clientes tem os dados do banco, chame ele onde precisar agora.    
$clientes = listarTodosClientes($db);

foreach($clientes as $item){
   echo $item['cli_nome'] . '<br>';
}
echo "--------------------- <br>"; 

foreach($clientes as $item){
   echo $item['cli_nome'] . '<br>';
}
    
asked by anonymous 14.07.2017 / 00:14

1 answer

0

If I understand correctly you want something of the type

function listarTodosClientes($db,$id=0){
    $sql = 'select * from cliente';
    if(!empty($id)){
        $sql.= " WHERE cli_id  = ".$id;
    }
    $res = mysql_query($sql) or die(mysql_error());

    $lista = array();
    while($item = mysql_fetch_assoc($res)){
       $lista[] = $item;
   }

    return $lista;
}

A few note these methods mysql_query and mysql_error are deprecated

    
14.07.2017 / 12:39