0
When I try to make a request to return an sql query to the form fields it returns only the first row of the table, how can I change my code to fetch all rows:
select code:
<?php
class Medico
{
public $nome;
}
try
{
require "conexaoMysql.php";
$medico = "";
$especialidade = "";
if (isset($_POST["especialidade"]))
$especialidade = $_POST["especialidade"];
$SQL = "
SELECT Nome
FROM funcionario
WHERE Especialidade = '$especialidade';
";
if (! $result = $conn->query($SQL))
throw new Exception('Ocorreu uma falha ao buscar os nomes: ' . $conn-
>error);
if ($result->num_rows > 0)
{
$row = $result->fetch_assoc();
$medico = new Medico();
$medico->nome = $row["Nome"];
}
$jsonStr = json_encode($medico);
echo $jsonStr;
}
Code of the function making the request
function buscaNome(especialidade)
{
$("#nomeEsp").empty();
$.ajax({
url: 'php/buscaNomes.php',
type: 'POST',
async: true,
dataType: 'json',
data: {'especialidade':especialidade},
success: function(result) {
if (result != "")
{
var campoSelect = document.getElementById("nomeEsp");
var option = document.createElement("option");
option.text = result.nome;
option.value = result.nome;
campoSelect.add(option);
}
},
error: function(xhr, status, error) {
alert(status + error + xhr.responseText);
}
});
}
Note: The results are placed in a select html field
With the changes, you have not listed any results in the form field.
– Bruno Inácio
Appears "Undefined"
– Bruno Inácio
I edited the answer to solve the Undefined problem. Basically json_encode was not creating private attributes of its medical class.
– Juven_v
I made the changes, but it keeps appearing only "Undefined".
– Bruno Inácio