PHP Mysqli Array in select html

Asked

Viewed 552 times

3

I’m a beginner in php and I’m developing a small system for my company and that already serves as a study, because I like this area, doubt is simple, I have the code below:

<?php
include('conn/conexao.php');
$edt = $_GET['edital'];
$sql = "SELECT * FROM edt_cadastro WHERE id = $edt";
$res = $mysqli->query($sql);
$num = $res->num_rows;

for ($i = 0; $i < $num; $i++) {
  $dados = $res->fetch_array();
  $arrRefs[$dados['id']] = $dados['ref0'];
}
?>

<label>Referências:</label>
<select name="ref" id="ref">
  <?php foreach($arrRefs as $value => $nome){
    echo "<option value='{$value}'>{$nome}</option>";
  }
?>
</select>

with this code it identifies the option of a previous select to load this select above (with jQuery), until then it works right, only that the value that comes from the database for this select, comes as an array example "1,2,3" i would like it to show me a list with 1 after 2, 3 and so on, in the bank is separated with comma "," (1,2,3) I have already tried to use the option explodes but then in the list only appears the last record in my example the number 3. could anyone help? thank you

  • 1

    Guys got it, with the following Cod: <? php include('Conn/connected.php'); $edt = $_GET['edict']; $sql = "SELECT * FROM edt_registration WHERE id = $edt"; $res = $mysqli-query>($sql); $i = 0; ? > <label>References:</label> <select name="ref" id="ref"> <?php while ($Row = $res->fetch_array()) { $references = $Row['ref0']; $quantity_ref = explodes(",",$references); $total=Count($quantity_ref); $n = 0; while($n < $total) { $i++ echo '<option value="'. $i.'">'. $quantity_ref[$n]; $n++; } } ? > </select>

  • 3

    Denis, if you have solved it you can put the solution as an answer (not a comment) or you can delete the question. Good New Year!

1 answer

2

I did, with the following Cod:

<?php           
include('conn/conexao.php');
$edt = $_GET['edital'];
$sql = "SELECT * FROM edt_cadastro WHERE id = $edt";
$res = $mysqli->query($sql);
$i = 0;
?>
<label>Referências:</label>
    <select name="ref" id="ref">
        <?php while ($row = $res->fetch_array()) {
            $referencias = $row['ref0'];
            $quantidade_ref = explode(",",$referencias);
            $total=count($quantidade_ref);
            $n = 0;
            while($n < $total) {
                $i++;
                echo '<option value="'.$i.'">'.$quantidade_ref[$n];
                $n++;
            }           
        }?>
    </select> 
  • 1

    I recommend not using the query as you are doing. Read about Preparedstatement.

  • 1

    Wouldn’t it be better to eliminate the $n and simply do echo '<option value="'.$i.'">'.$quantidade_ref[++$i]; ? Or better yet, instead of while($n<$total) one for($i=0; $i<$total;$i++)...

Browser other questions tagged

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