Get Bank ID to load in HTML select

1

How can I get hold of Bank ID to load in HTML select

My function like this:

public function ComboBox($sql, $idcampo, $selected)
{
     $cn = conexao::getInstance()->prepare($sql);
     echo "<select name='" . $idcampo . "'>";
     $selec = "";
     while ($row = $cn->fetch(PDO::FETCH_ASSOC)) {
         if ($row[1] == $selected) {
             $selec = " selected";
         } else {
             $selec = "";
         }
         echo "<option value='" . $row[1] . "'" . $selec . ">" . $row[2] . "</option>";
     }
     echo "</select>";
 }

When calling the function and passing $ sql, $ idcampo and status (selected or not).

I call it to generate the select to select the value to do the insertion, I just do not know how to get the $ field from the insert page, because it would need to load all $ id's from the database to populate the select in HTML.

In call: <?php echo $objct->ComboBox('select id, nome from cliente', $objcli->getIdcli(), 0); ?>

    
asked by anonymous 29.08.2018 / 14:25

1 answer

2

Maybe the issue is not well worked out, because I do not completely understand what the problem is, but what I understand about your parameters is

$sql - SQL que vai retornar os resultados para preencher o <select> com valores
$idcampo - O nome do campo a dar ao <select> (pode ser qualquer coisa!)
$selected - O valor que deve ficar seleccionado no render

At this point you have <?php echo $objct->ComboBox('select id, nome from cliente', $objcli->getIdcli(), 0); ?> , that is, you are passing the ID of the $objcli object to the field to be used, presumably the HTML in the page is something like <select name="21"> (if it is the value returned by $objcli->getIdcli() ), and should be something like <select name="id"> .

For this, your call would actually have to be something like <?php echo $objcli->ComboBox('select id, nome from cliente', 'id', $objcli->getIdcli()); ?>

However, the form where this <select> is, when it is submitted and you want to know which value was chosen, just use $_POST (or $_GET ), for example, if you passed $idcampo it will be 'id' and from there you will do what you need with that value.

//

PDO :: FETCH_ASSOC

$_POST['id'] returns an array with field names as index.

// Exemplo
Array
(
    [id] => 1
    [nome] => Jão
)

In your PDO::FETCH_ASSOC function, you use ComboBox , which should actually be giving error, Undefined index . You should probably use $row[1] , which gives you something like

Array
(
    [id] => 1
    [0] => 1
    [nome] => Jão
    [1] => Jão
)

And with this result, in the function you should change the PDO::FETCH_BOTH to $row[1] and $row[0] to $row[2] (since it is a 0 based array).

The value to pass in $row[1] can be only a string, you can only $idcampo and should work correctly.

    
29.08.2018 / 15:02