Search ID in a PHP select

Asked

Viewed 547 times

-1

<select class="form-control" name="cliente">
    <?php if ($clientes) {
        foreach($clientes as $ind => $valor) {
     ?>
        <option value="<?php echo $valor->nome ?>"><?php echo $valor->nome ?></option>
    <?php } } ?>
</select>

I would like to understand this code, everything indicates that it makes a select and brings the list to perform a registration.

  • What the above code does is to check if there is any value in the $clients variable and if there is it prints the clients name in a select. Creating a select of customer names!

  • This code is creating the options of a dropdow(Select) but without knowing the whole scope of the application it is difficult to know what the purpose of using it is. By the way you should know where this comes from...

  • this if validation ($clients) is not very good. leaves gap for errors. For example: $clients = [array()]; it would pass its validation and generate the following error in its foreach: "NOTICE Trying to get Property of non-object on line number 7"

2 answers

3

<select class="form-control" name="cliente">
....
</select>

These lines are the opening and closing of the HTML tag to create a selection object (combo box or select) on the HTML page, not to perform a select on a database. Probably this select has already been performed at an earlier point in the code, not shown in your example.

<?php if ($clientes) {
    foreach($clientes as $ind => $valor) {
 ?>
    <option value="<?php echo $valor->nome ?>"><?php echo $valor->nome ?></option>
<?php } } ?>

In this code portion the combo box object is populated with the options. In the line with the if is tested if the $clients variable has a true value, in this case if it is the "result" of the bank search, if it is null it will be considered false and does not enter if, otherwise probably why it has return values, enter.

In the block of foreach each record of the query result is covered and the index placed in $ind and the registration in $valor. The line starting with the tag mounts the choice option that will be shown in the combo box object.

2


=> is used to associate key and value in a vector.

-> is used to access a method or property of an object.

<select class="form-control" name="cliente">
<?php 
   if ($clientes) {   //Se houver algum cliente ele entra no IF
      foreach($clientes as $ind => $valor) { //Para cada cliente ele criará uma opção
         ?>
            <option value="<?php echo $valor->nome ?>"> <!--Seta o valor da opção com propriedade nome do objeto valor. -->
               <?php echo $valor->nome ?> <!--Exibe a propriedade nome do objeto valor.-->
            </option>
         <?php 
      } 
   } 
?>
</select>

Browser other questions tagged

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