-1

I'm wanting to search database for existing strings when typing into a <input>

I currently have this input code:

<input type="text" name="rules_data_imdb_id" value="" id="elInput_rules_data_imdb_id">

With this PHP:

$mysqli = new mysqli(localhost, username, password, database);
$result = $mysqli->query("SELECT id FROM rules_data_videobox_video WHERE data_imdb_id = '#elInput_rules_data_imdb_id'");
if($result->num_rows == 0) {
echo "<h2>exists</h2>";
} else {
echo "<h2>nah</h2>";
}
$mysqli->close();

However I'm just splicing together bits and bobs what I've seen on the internet as I rarely use PHP i'm not familiar with it.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Pornsera
  • 23
  • 4
  • 2
    If you are using javascript, you can use `ajax` to get data from the database. You can call the `ajax` function on every keypress using `onkeyup` or `onkeydown` or `onchange` depending on your use case. That should get you started. – Rob Moll Jun 25 '20 at 18:55
  • How was this closed due to duplicate question about checking if a row exists in MySQL? The question was about how to do a search when a user is typing in a html-field (input). This was not a query question? – MrApnea Jun 29 '20 at 08:29

1 Answers1

0

As Rob mentioned in a comment you can use ajax. Using JQuery is easy if you want to get started and haven't done this before. Then later on you can try a more raw approach or use another library.

https://api.jquery.com/jQuery.get/

When a user press a key in your input field you trigger with onchange (or another method) and send a request to your php-script. This script should work as an API and take your search term and only return the results. So in your onchange method you use ajax to call your api to get the results and update your page. Then it will update on each key.

BUT, this will work in theory. But in practice it's a bit more to it. If you write a word, lets say if you write "StackOverflow" as your searchterm really fast you will trigger 13 requests and that will make the page slow and there is no guarantee that the results will come back in order. One thing to do is to wait when a key is pressed. You could set a trigger with SetTimeout (https://www.w3schools.com/jsref/met_win_settimeout.asp) to run your search after 500ms and if a new key comes before that you clear the timeout and sets a new one. So if someone types fast you will only make one request when the user pauses or are done.

Dharman
  • 30,962
  • 25
  • 85
  • 135
MrApnea
  • 1,776
  • 1
  • 9
  • 17