I want to fill a <select>
with the data I have in the database. I already tried putting a script inside the HTML and it works, however, to make the code more readable and to be able to access the same data in other pages (the <select>
one in question is required in different pages) I have created a script that contains a function that in Theoretically, it should generate the fields <option>
, but when it is executed, it does not give the desired result, that is, it is not generated in the page in which I call it. The function code is:
<?php
include 'connection.php';
function GenerarDependencias(){
$sentence = "SELECT idDependencia, Nombre FROM Dependencias";
$departments = mysqli_query($connection, $sentence);
echo "<select>";
foreach ($departments as $d) {
echo "<option value=\"".$d['idDependencia']."\">".$d['Nombre']."</option>";
}
echo "</select>";
mysqli_close($connection);
}
?>
To call it in the page I put the following fragment
<?php GenerarDependencias(); ?>
As a result the page is generated, the only thing that does not appear is the data in the <select>
.
Note: Right before the start of the html file I place<?php include 'consultar.php' //script donde está la función ?>
The error was solved by sending the variable
$connection
to the function as a parameterGenerarDependencias();
since it is not available for the function. Contributed by @Triby