How to select an option in select less laborious way?

2

I have a page called editarpublicacao.php which receives id through GET .

One of the two <select> for example contained in the page, is similar to that of the companies:

<select name="company" data-placeholder="Selecione" class="form-control chosen-select" id="cmbCompany" required data-parsley-errors-container="#company-errors">
  <option value="" selected disabled hidden>Selecione</option>
  <?php 
  $companies = $searchSQL->fetchAll(PDO::FETCH_ASSOC);
  foreach ($companies as $empresas):
  ?>
    <option value="<?php echo $empresas['id_Company'];?>"><?php echo $empresas['razaoSocial']; ?></option>
  <?php endforeach; ?>
</select>

And I show all companies through PHP using while in that.

But for example, if I get in $_GET['id'] , a id value of 12,

How to show all companies and select one of them? In an example case, that of id == 12, it must be automatically selected.

If id == 12 was that of so-and-so, I had to show all companies and select so-and-so, even in this snippet I did:

<select name="select">
  <option value="valor1">Valor</option> 
  <option value="valor2" selected>Fulano</option>
  <option value="valor3">Valor 3</option>
</select>

I have the query that selects all companies:

$searchSQL = $pdo->prepare("SELECT id_Company, razaoSocial FROM tbl_company ORDER by razaoSocial ASC");
$searchSQL->execute(); 

How to do this, to show all companies and select one of them, that has the id equal to the one received by $ _GET?

I saw in this [link] [1] what I can do like this:

<option value="January"<?=$row['month'] == 'January' ? ' selected="selected"' : '';?>>January</option>

There you have problems doing so, what if I had 1000 records? Is not there an easier way to do it? And how can I do it?

    
asked by anonymous 29.09.2017 / 17:43

1 answer

0

I think this can solve your problem, it will leave the one with the ID equal to the GET id selected as

<select name="company" data-placeholder="Selecione" class="form-control chosen-select" id="cmbCompany" required data-parsley-errors-container="#company-errors">
  <option value="" selected disabled hidden>Selecione</option>
  <?php 
  $companies = $searchSQL->fetchAll(PDO::FETCH_ASSOC);
  foreach ($companies as $empresas):
  if($empresas['id_Company'] == $_GET['id']){
  ?>
    <option value="<?php echo $empresas['id_Company'];?>" selected><?php echo $empresas['razaoSocial']; ?></option>
  <?}else{ ?>
    <option value="<?php echo $empresas['id_Company'];?>"><?php echo $empresas['razaoSocial']; ?></option>
  <?}?>
  <?php endforeach; ?>
</select>
    
03.10.2017 / 23:14