I am trying to add an selected
to option
when there is a client ID, otherwise it goes to the default <option value="">Por favor, seleccioné un cliente...</option>
, it works fine when adding the selected
, but the problem is that it option
appears twice, it duplicates it separately, it is generating the wrong HTML structure of the selected
-> option
.
This is my code:
$get_id = 3;
$stmt = $con->prepare("SELECT
id_cliente,
nombre_cliente
FROM cliente");
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows>0) {
$stmt->bind_result(
$id_cliente,
$nombre_cliente
);
$select = '';
$select .= '<select name="id_cliente">';
$select .= '<option value="">Por favor, seleccioné un cliente...</option>';
while ($stmt->fetch()) {
if(1) {
$select .= '<option value="'.$id_cliente.'"'; if($id_cliente === $get_id) $select .= 'selected="selected">'.$nombre_cliente.'</option>';
}
$select .= '<option value="'.$id_cliente.'">'.$nombre_cliente.'</option>';
}
$select .= '</select>';
echo $select;
}
And, this is the result that is generating me:
<select name="id_cliente">
<option value="">Por favor, seleccioné un cliente...</option>
<option value="2"<option value="2">Cliente 1.</option>
<option value="3"selected="selected">Cliente 2.</option>
<option value="3">Cliente 3.</option>
<option value="4"<option value="4">Cliente 4.</option><option value="16"<option value="16">Cliente 5.</option>
<option value="17"<option value="17">Cliente 6.</option>
</select>
Concatenations are a real mess in these cases. The HTML output shows that you are not closing the <tag>
option
and more things than parsing them in your code give you a headache and that is not a very long code...I recommend that for these cases you simplify. It's much better to use double quotes for the whole string , so you can wrap variables inside the string, and you can escape double quotes from elements like
value=\"...\"
.On the other hand, I don't know what's the point of your
if(1)
, it's useless. And to determine what heoption
should wear,selected
you can use a ternary that does the evaluation, assigning nothing or the wordselected
when the criteria is met.The code becomes simpler, cleaner, and easier to debug: