PHP + MYSQL autocomplete - returning ID

Asked

Viewed 965 times

0

I’m developing an application for college, and I came across the following problem:

I have to search used autocomplete passing as parameter the name of the doctor, so recover the id of the same and save in the bank. I have tried every way but I can not recover the id, only the autocomplete works.

Example

In PHP

<div class="form-group">
    <label>Profissional</label>

    <input type="text" name="prof" value="" class="form-control"   placeholder="Insira o nome do Profissional." id="txtProf" class="typeahead">
    <input type="hidden" name="idprof" value="" class="form-control"  id="idprof" >
</div>

<div class="form-group">
    <label >Procedimento</label>
    <input type="text" name="proced" value="" class="form-control"   placeholder="Insira o nome do Procedimento." id="txtProc" class="typeahead">
</div>

In Javascript:

$(document).ready(function () {
    $('#txtProf').typeahead({
        source: function (query, result) {
            $.ajax({
                url: "../classes/db/server.php",
                data: 'query=' + query,            
                dataType: "json",
                type: "POST",
                success: function (data) {
                  result($.map(data, function (item) {
                    return item;
                    }));
                }
            });
        }
    });
});

And in the search file (server.php):

$keyword = strval($_POST['query']);
$search_param = "{$keyword}%";
$conn =new mysqli('localhost', 'root', '' , 'clinicanova');

$sql = $conn->prepare("SELECT pf.nome FROM tb_pessoa pf, tb_profissional prof
                         WHERE pf.id = prof.tb_pessoa_id
                         and prof.status = 'A'
                         and pf.nome LIKE ?");
$sql->bind_param("s",$search_param);            
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
    $countryResult[] = $row["nome"];
    }
    echo json_encode($countryResult);

}
$conn->close();

Wanted a way to complete the ID field with the data the user selects.

READY I WAS ABLE TO RESCUE THE ID SO MISSING POPULATE INSIDE HIDDEN knows how I can do it because adding straight to the result does not work MY JAVASCRIPT IS LIKE THIS NOW:

<script>
$(document).ready(function () {
    $('#txtProf').typeahead({
        source: function (query, result) {
            $.ajax({
                url: "../classes/db/server.php",
                data: 'query=' + query,            
                dataType: "json",
                type: "POST",
                success: function (data) {
        result($.map(data, function (item) {
          return item.nome;
           $('#idprof').val(item.id);
                    }));
                }
            });
        }
    });
});

HOW DO I INSERT THIS "item.id" into an input

  • First you have to retrieve and store the ID in the variable countryResult. Your select is only returning the pf.nome

  • sorry to be unaware, I’m getting used to the language now I don’t know if I did right but I changed the code to: if ($result->num_rows > 0) { while($Row = $result->fetch_assoc()) { $countryResult[] = $Row["name"]; $countryResult[] = $Row["id"]; }

  • I did not understand how this logic works, to pass and how to recover there js and work in the form

1 answer

1


To return data from id and nome of the professional, we must inform the query sql these fields. Ex:

/* Aqui utilizarei uma lib do Typehead para auxiliar. Essa lib irá nos auxiliar com os requests */
var profissionais = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('nome'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  /* Aqui eu defino a URL do JSON e o termo. Nesse caso eu utilizarei GET e não POST */
  prefetch: 'https://api.myjson.com/bins/fn5wb', /* Substitua APENAS "https://api.myjson.com/bins/fn5wb". */
  remote: {
    url: 'https://api.myjson.com/bins/fn5wb?query=%query', /* Substitua APENAS "https://api.myjson.com/bins/fn5wb". */
    'wildcard': '%query'
  }
});

$('#lista-profissionais .typeahead').typeahead(null, {
  name: 'profissionais',
  display: 'nome',
  source: profissionais
});

/* Esse evento irá capturar o resultado do nome e ID */
$('#lista-profissionais .typeahead').bind('typeahead:select', function(ev, suggestion) {
  $("#idprof").val(suggestion.id);

  alert("Nome: " + suggestion.nome + "\nId: " + suggestion.id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.11.1/typeahead.bundle.min.js"></script>

<div id="lista-profissionais">
  <input type="hidden" name="idprof" value="" class="form-control" id="idprof">
  <input class="typeahead" type="text" placeholder="Informe o nome do profissional">
</div>

php server.

$keyword = strval($_GET['query']);

$conn = new mysqli('localhost', 'root', '', 'clinicanova');

/* Aqui informamos que devemos capturar o ID e o NOME do profissional. */
$sql = $conn->prepare("SELECT pf.id AS `id`, pf.nome AS `nome` FROM tb_pessoa pf, tb_profissional prof
                         WHERE pf.id = prof.tb_pessoa_id
                         and prof.status = 'A'
                         and pf.nome LIKE ?");

$sql->bind_param("s", "{$keyword}%");            

$sql->execute();

$result = $sql->get_result();

$countryResult = [];

while($row = $result->fetch_assoc()) {

    /* Aqui montamos o array com os dados que serão exibidos */
    $countryResult[] = [
            "id" => $row["id"], //Verifique se esse index realmente existe.
            "nome" => $row["nome"], //Verifique se esse index realmente existe.
    ];
}

echo json_encode($countryResult);

$conn->close();

I added a json that wasn’t from server.php to make it functional here on the site, but you should change the URL for the server.php

To test the php server., access https://www.example.com/server.php?query=A, if it is working, check if the URL on javascript is correct.

  • friend did not work very well, does not load the data!

  • I edited my reply. I added some information.

  • friend performed the modification and does not work, I do not know if I’m too dumb, pq theoretically and for right but the page does not load the autocomplete, knows another way to use this autocomplete and rescue for a Hidden the id of what the user choose

  • Edit your question and post your "new" code, as you are doing this time. You have tested only the server.php?

  • updated my reply, I was able to rescue the ID would like to know how to set it in an input now

  • @Valdeirpsr, would it be possible to perform some function if the user does not choose any of the data coming from the database? Like, I need the information necessarily to come from the bank, not letting the user type a different

  • @Marcospaulo You can add a validation to the server. If the value is not found in the database, it returns an error to the user.

Show 2 more comments

Browser other questions tagged

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