Use While twice or more for the same Select?

Asked

Viewed 547 times

0

I’m setting up a listing page and registration of output products and I’m having trouble at the time to pull up the information and do the while for the 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 would be to show inside a select option with all customers

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

Here would be to show inside a select option and here only active customers

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

Now comes the problem: the idea was to make another while taking advantage of the query existing and pull customer data by id, but I could not find a scheme to make a function. It repeats the data obtained in the first query. I couldn’t filter the information.

Follow 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>';
}
  • Get customer data? but these are not already in the customer table?

  • A note, the second query is with a typo, $sql_for2 = mysql_query ("SELECT * FROM cliente WHERE cli_status='on'); is missing the closure of double quotes ". $sql_for2 = mysql_query ("SELECT * FROM cliente WHERE cli_status='on'");

1 answer

1

If I understand correctly you want something like

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 peguena note these methods mysql_query and mysql_error are deprecated

Browser other questions tagged

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