When the user selects an element from the combobox, it is an activity that occurs on the client side (i.e., from the browser), and the code that runs on the server, PHP, does not and cannot be aware of when this happens.
Therefore, we need code that runs on the client, that is, javascript, that will address this issue. Let’s say the code that creates the combobox and the text box are below:
$query = "SELECT nome FROM Medicos";
$data = mysqli_query($dbconn, $query);
$result = mysqli_num_rows($data);
?>
<form name="medicos" method="post" action="administrador_medicos_populate.php">
<label for="cbMedicos">Selecione um Medico</label>
<select id="cbMedicos">
<option>Selecione...</option>
<?php while($prod = $data->fetch_assoc()) {
echo '<option value="'.$prod['nome'].'">'.$prod['nome'].'</option>';
}
?>
</select>
<input type="text" id="txtMedico" value="" />
We need to proceed with a code that takes the value of the combobox cbMedicos
and put it in the text box txtMedico
, when that changes. For that, we need a tag <script>
.
Ordinarily, I would say to put the tags <script>
within the tag <head>
, but then we would need to listen to a second event to hope that the page was created before tying the event in the cbMedicos
; then put the following code on your page at some point afterward where you define cbMedicos
:
<script type="text/javascript">
document.getElementById("cbMedicos").addEventListener("change", function () {
document.getElementById("txtMedico").value = this.value;
});
</script>
This code gets a reference to the combobox through your id using getElementById()
, and adds an event using addEventListener()
for the event change
. When the value of the combobox changes, it will perform this function which is the second parameter of addEventListener()
.
Inside the function, the pointer this
points to the combobox itself, then we get a reference to the text box using the same document.getElementById()
and assign to its value the value of the combobox (property .value
).
Adapt the code here to your situation and see if it works.
To bring various information:
If you want to bring various information from various physicians, there are many options, but possibly the ideal is to serialize your information to JSON using json_serialize()
and assign to a javascript variable, that the event of onchange
from the combobox will use to popular all other controls:
<html lang="pt-pt">
<head>
</head>
<body>
<?php
$servername = "localhost";
$username = "isabelso_isabel";
$password = "password";
$dbname = "isabelso_db";
$dbconn = mysqli_connect($servername, $username, $password, $dbname)or die("Failed to connect to database:" . mysqli_error($dbconn));
// vamos dar um alias para cada coluna conforme o nome do
$query = "SELECT nome as txtNome, email as txtEmail /*, etc. */ FROM Medicos";
$data = mysqli_query($dbconn, $query);
$result = mysqli_num_rows($data);
$meujson = array();
?>
<form name="medicos" method="post" action="">
<label for="cbMedicos">Selecione um Medico</label>
<select id="cbMedicos">
<option>Selecione...</option>
<?php while($prod = $data->fetch_assoc()) {
echo '<option value="'.$prod['txtNome'].'">'.$prod['txtNome'].'</option>';
$meujson[$prod['txtNome']] = $prod; // coleciona as linhas no $meujson
}
?>
</select>
<label for="txtNome">Nome:</label>
<input type="text" id="txtNome" value="" />
<label for="txtNome">Email:</label>
<input type="text" id="txtEmail" value="" />
<!-- etc. -->
</form>
<script type="text/javascript">
// Armazenar a coleção de dados (chaveada por nome) numa variável javascript
var dados = <?php echo json_encode($meujson); ?>;
document.getElementById("cbMedicos").addEventListener("change", function ()
{
// obtém a linha referente ao médico selecionado
var linha = dados[this.value];
// a forma "for (<variável> in <objeto>) itera sobre as chaves
// (nomes de propriedades) do objeto mencionado,
// e põe cada uma na variável de índice por vez
for (var ch in linha) {
(document.getElementById(ch) || {}).value = linha[ch];
}
});
</script>
I mean, I’m creating in PHP a array()
I will use as a dictionary to collect all the information of all the doctors, changed by the name of the professional (could be by the table id, in this case we would have to bring it also from the bank).
After that, in the <script>
, We created a variable that will store all this information. To do so, we write the information we collect as JSON (javascript object notation) which is conveniently the syntax of creating object literals in javascript. Thus, dados
is a variable that contains all the information we will need to fill out for each doctor - just be careful so there are no doctors or too much information, otherwise the page will get heavy. If we stay, we will have to change strategy and bring the information asymptotically using AJAX, probably.
Finally, at the event change
from the combobox, we took the object element dados
that corresponds to the selected doctor (remember that $meujson
and therefore dados
is a dictionary whose keys are the names of the doctors) and we iterated on the keys of this document, which on purpose are the Ids of the controls that must be filled by them, ticking each in turn.
Two details:
First, the form for (
variablein
object)
iterate on the keys, not on the values of object. Then, you still have to de-reference the object to get the value corresponding to the key (using the index operator []
, just like PHP arrays).
For example, if you have an object obj = { a: 1, b: 2 };
and you say for (var i in obj) { alert(i); }
, two will appear popups message, one saying "a" and the other "b". To get "1" and "2", we would have to say for (var i in obj) { alert(obj[i]); }
.
Second, the game of (
object|| {})
is a trick similar to or die()
of PHP: if the document.getElementById(ch)
fail, because there is no control with an ID equal to the key in question, it returns a value null
; if we tried to assign something to the property value
of null
we would make a mistake and the execution of script would stop. However, how null
is equivalent to false, we apply an operator or
(that is written in javascript ||
) and an empty object {}
.
Thus, if a control with a given id does not exist, document.getElementById(ch)
returns null
, but (document.getElementById(ch) || {})
returns {}
, which is an empty object, and the property will be assigned to it and then it will be discarded and collected by the garbage collector, without raising error.
When you run, returns some kind of error?
– Seu Madruga
@inovapixel the page is blank
– Isabel Sousa
Have you entered the bank connection credentials? I see no problems in the code.
– Seu Madruga
@inovapixel At the level of the blank page I already solved, it was my mistake in another part of the code... but now in this part: you are doing nothing! with the code as it is, when selecting a name of the combobox should already pass the name, to the textbox "name", right?
– Isabel Sousa
You certainly shouldn’t, and you won’t until there’s a code javascript to do so at the event
onchange
of the combobox. This has not even an id, so it should hardly have the event armed...– Wtrmute
Do you want to pass the value of select to an input type text? If so, you will need to use javascript
– Seu Madruga
@inovapixel I want that when selecting a combobox name you pass all the data that are in the database that name to the respective textboxs so that later you can delete or edit...
– Isabel Sousa
@wtrmute never used javascript, just as php is the first time... It will be possible to exemplify?
– Isabel Sousa
What you want to do is more complex; it requires a new algorithm. If you don’t understand javascript and php, it would be somewhat complicated to do. This requires a lot more lines than these. I have no way to exemplify here, I’m running out of time. I came here to see if a question of mine already has an answer; sorry, Isabel.
– Seu Madruga