I made an autocomplete search box that suggests words from a mysql table column as i type but the problem is that it works only if i limit the sql query at approx 1200...and i have about 2500 records. After 1200 it becomes unresponsive. I indexed the column as FULLTEXT and here is the code i use:
The HTML:
<script type="text/javascript">
$(function() {
var availableTags = <?php include('autocomplete.php'); ?>;
$("#furnizor").autocomplete({
source: availableTags,
autoFocus:true
});
});
</script>
<input id="furnizor" type="text" size="50" />
And here is the php script 'autocomplete.php':
<?php
$connection = mysqli_connect("localhost","user","password","database") or die("Error " . mysqli_error($connection));
$sql1 = "select distinct name from search";
$result_search = mysqli_query($connection, $sql1) or die("Error " . mysqli_error($connection));
$dname_list = array();
while($row = mysqli_fetch_array($result_search))
{
$dname_list[] = $row['name'];
}
echo json_encode($dname_list);
?>
The table is named 'search' and the column i search in is named 'name'.
So all this works if i limit the sql query to 1200...everything over that number becomes unresponsive.
Is there a way to make this work for about 2500 records?
Related
I'm doing my best to put together a basic property management app that will allow users to check out keys to contractors (and check them back in of course). I'm a relatively inexperienced coder and am currently struggling to work out how to pass an additional SQL ID value during a lookup.
The user can currently search for a contractor name and company in the 'searchcontractor' input. The backend-search.php file populates this input with FirstName, LastName and Company from the Contractors database, but I cannot work out how to also pass that record's ContractorID value into a hidden input 'contractorid'.
Would hugely appreciate any pointers, thank you.
PHP
<?php
include "msbkeys.php";
$sql = "SELECT KeySets.KeySetID, KeySets.KeyDescription, Sites.SiteID, Sites.SiteName FROM Sites INNER JOIN KeySets ON Sites.SiteID=KeySets.SiteID WHERE KeySets.KeyAssignedTo IS NULL;";
$result = $db->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>Keyset ID</th><th>Site ID</th><th>Site name</th><th>Description</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
$keysetidsubmit = $row['KeySetID'];
echo "<tr><td>".$row["KeySetID"]."</td><td>".$row["SiteID"]."</td><td> ".$row["SiteName"]."</td><td> ".$row["KeyDescription"]."</td><td> <form method='post'><input type='hidden' name='keysetid' value=".$keysetidsubmit."><div class='search-box'>
<input name='searchcontractor' type='text' autocomplete='off' placeholder='Search contractor...' />
<div class='result'></div>
</div><input type='hidden' name='contractorid' value="**how can I populate this with the ID of the contractor chosen in the searchcontractor input?**"> <input name='checkoutkey' type='submit' value='Check out key'></form> </td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
mysqli_close($db); // Close connection
?>
JavaScript
<script>
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input", function(){
/* Get input value on change */
var inputVal = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(inputVal.length){
$.get("backend-search.php", {term: inputVal}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
// Set search input value on click of result item
$(document).on("click", ".result p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
</script>
backend-search.php
<?php
include "msbkeys.php";
if(isset($_REQUEST["term"])){
// Prepare a select statement
$sql = "SELECT * FROM Contractors WHERE CONCAT (FirstName,' ',LastName) LIKE ?";
if($stmt = mysqli_prepare($db, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_term);
// Set parameters
$param_term = $_REQUEST["term"] . '%';
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_get_result($stmt);
// Check number of rows in the result set
if(mysqli_num_rows($result) > 0){
// Fetch result rows as an associative array
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<p>" . $row["FirstName"]." ".$row["LastName"] ." (".$row["Company"].")</p>";
}
} else{
echo "<p>No matches found</p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// close connection
mysqli_close($db);
?>
Add the contractor ID as an attribute in the <p> containing the contractor name.
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<p data-contractorid='{$row["id"]}'>" . $row["FirstName"]." ".$row["LastName"] ." (".$row["Company"].")</p>";
}
Replace $row["id"] with the actual column name of the contractor ID.
Then copy this to the hidden input field.
$(document).on("click", ".result p", function(){
$(this).closest(".search-box").find('input[type="text"]').val($(this).text());
$(this).closest("td").find('input[name=contractorid]').val($(this).data('contractorid'));
$(this).parent(".result").empty();
});
I want to do text autocomplete using php and html..
i have tried the below code
<?php
$connection = mysqli_connect("localhost", "root", "pass", "data") or die("Error " . mysqli_error($connection));
$sql = "select value from fin";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dna = array();
while ($row = mysqli_fetch_array($result))
{
$dna[] = $row['value'];
}
$jj = array_unique($dna);
print_r(array_values($jj));
?>
result is
my html
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/
themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4
/jquery-ui.js">
</script>
</head>
<body>
<form name="vinform" method="get"> <input type="text" name="editor" autocomplete="on"> <input type="submit" value="Show" id="display"> </form>
<div id="div1"></div>
<script type="text/javascript">
$(function() {
$('#div1').autocomplete({
source: "auto.php"
});
});
</script>
</body>
it doesn't show the words from mysql when i type some word in the text field ..i have to show the related words from mysql based on the text field input,when i type a character in the text field..can anyone help me to solve the issue in my code?
tried with Ajax
var se = null;
$(function () {
var minlength = 1;
$("#editor").keyup(function () {
var that = this,
value = $(this).val();
if (value.length >= minlength ) {
if (se != null)
se.abort();
se = $.ajax({
type: "GET",
url: "auto.php",
data: value,
dataType: "text",
success: function(msg){
if (value==$(that).val()) {
}
}
});
}
});
});
php
<?php
if(isset($_GET['editor']))
{
$con=mysqli_connect("localhost","root","admin321","data");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name=$_GET['editor'];
$sql = "select value from fin where value LIKE '%".$name."'";
$result = mysqli_query($connection, $sql) or
die("Error " . mysqli_error($connection));
$dna = array();
while($row = mysqli_fetch_array($result))
{
$dna[] = $row['value'];
}
$jj=array_unique($dna);
print_r ( $jj);
}
?>
no autocomplete action
With option 1 (Jquery UI autocomplete) and try something like that
<?php
$connection = mysqli_connect("localhost", "root", "pass", "data") or die("Error " . mysqli_error($connection));
$sql = "select value from fin";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dna = array();
while ($row = mysqli_fetch_array($result))
{
$dna[] = $row['value'];
}
echo json_encode($dna);
?>
Jquery UI autocomplete state about source option
String: When a string is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The Autocomplete plugin does not filter the results, instead a query string is added with a term field, which the server-side script should use for filtering the results. For example, if the source option is set to "http://example.com" and the user types foo, a GET request would be made to http://example.com?term=foo. The data itself can be in the same format as the local data described above.
You can use AJAX and Jquery..in html code call the function on keyup event and send data using ajax request after that get data from database using LIKE query and display it..
in input add id="editor"
<input type="text" id="editor" name="editor" autocomplete="on">
I'm using jquery UI autocomplete for a search on my site. It's working properly without any problems while is on localhost. But on the live server it doesn't get any results. I have reviewed many posts on this topic, but I am still stymied as to why this doesn't work. I don't know if I can tell you the name of web hosting I use or not.
HTML code: index.php
<input type="text" placeholder="" name="ser" class="form-control" id="hotels" value="" required />
javascript code
<script type="text/javascript">
$(function() {
$( "#hotels" ).autocomplete({
source: 'scripts/chresults.php'
});
});
</script>
chresults.php
<?php
$dbHost = '';
$dbUsername = '';
$dbPassword = '';
$dbName = '';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$query = $db->query("SELECT * FROM hotels WHERE hotel LIKE '%".$searchTerm."%' or hotelen LIKE '%".$searchTerm."%' or city LIKE '%".$searchTerm."%'limit 5") or die ('mysql_error');
while ($row = $query->fetch_assoc())
{
$results['city'] = $row['city'];
$results[] = $row['hotel'].' , '.$row['city'];
}
//return json data
$json_string = json_encode($results, JSON_PRETTY_PRINT);
echo $json_string;
?>
I have this modal jQuery AJAX:
$('#switch_modal').on('show.bs.modal', function (e) {
var rowid = $(e.relatedTarget).attr('data-id');
$.ajax({
type : 'post', // commented for this demo
url : 'pars.php', // commented for this demo
data : 'id='+ rowid,
success : function(data) {
$('.fetched-data').show().html(rowid); // show rowid for this demo
}
});
});
My mysql query:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
while ($row = $result->fetch_assoc()) {
My modal data-id:
<a href="#viewgame" data-toggle="modal" data-id="<?php echo $row['id'];?>"">
How can i do to use the var rowid like a PHP post? Something like that:
$id = $_POST['rowid'];
echo $id;
If i understand well this test your doing...
Your JavaScript rowid is the value.
The $_POST identifier is id.
Try this in your PHP:
$id = $_POST['id'];
echo $id;
You'll get the javascript rowid sent as a POST value (named as $_POST['id']) via ajax... And returning in data on ajax success.
$('.fetched-data').show().html(data);
So you'll have to use data in your jQuery html()... Wich is the echoed text.
-----
EDIT AFTER ACCEPTATION of this answer
(Based on your last comment)
So i have this query:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
if ($result = $conn->query($query)) {
while ($row = $result->fetch_assoc()) {
$gameid = $row['id'];
}
}
So i want to use $gameid variable into this query:
$sql = "SELECT * FROM games WHERE id='".$gameid."'";
I understand, that you want to get THE LAST matching full line where winner value is empty from games table.
No need for an ajax call...
No need for a second query.
Just do it:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
$result = $conn->query($query);
$row = $result->fetch_assoc();
for ($i=0;$i<sizeOf($row);$i++){ // This is the «size» (number of values) of one row, the last fetched.
echo $row[$i] . "<br>";
}
You'll get all your line values echoed...
This will be the LAST matching line fetched.
If you have many matching lines and want all results, do it like this:
$query="SELECT * FROM games WHERE winner='' ORDER BY amount DESC";
$result = $conn->query($query));
while ($row = $result->fetch_assoc()) { // While fetching, echo all values of one matching line.
echo "row id: " . $row['id'] . "<br>";
echo "values: <br>";
for ($i=0;$i<sizeOf($row);$i++){
echo $row[$i] . "<br>";
}
}
Notice that this script, that I suggest, will enlight you about the while fetch loop possible results. You'll have to work a little to have it displayed correctly on your page.
;)
I have a form where I want the user to select an Organization from a SQL table and when the form is submitted, the ID of the selected organization should be saved to a different table. I researched online and on SO, and this is what I have now. And it does not work. What's wrong?
Newbrand.php:
<form action="newbrand.php" method="post">
Brand Name: <input type="text" name="bname" /><br><br>
Ogranization: <input type="text" name="searchbar" id="searchbar"><br><br>
<script>
$("#searchbar").keyup(function(){
var searchTerm = $(this).val();
$.post('search.php', { search_term: searchTerm}, function(data){
$(".searchResults").html(data);
$("#searchUl").css("display", "block");
});
});
</script>
Organization ID: <input type="hidden" name="gid" value="" /><br><br>
Gallery ID: <input type="text" name="gid" /><br><br>
</form>
Search.php:
<?php
include 'db_connect.php';
$link = mysqli_connect($host, $username, $password, $db);
$search_term = sanitize(htmlentities($_POST['search_term']));
if (!empty($search_term)){
$search = "(SELECT `Organization_Name` FROM `organizations_info` WHERE `Organization_Name` LIKE '%$search_term%' LIMIT 0, 5) ";
$query = mysqli_query($link, $search);
$result = mysqli_num_rows($query);
while ($row = mysqli_fetch_assoc($query)){
#$user_id = $row['user_id'];
#$username = $row['username'];
$orgname = $row['Organization_Name'];
$check = mysqli_num_rows($query);
if ($check != 0){
echo "<a style='text-decoration: none; color: black;' href='newbrand.php?band=$orgname'><li class='searchResults'>" . ucfirst($orgname) . "</li></a>";
} else {
echo "<li class='searchResults'>No Results Found</li>";
}
}
}
?>
The problem is with your query. It's not passing the value of $search_term, but rather passing it as a string. You may want to use prepared statements and bind the parameter first:
$stmt = mysqli_prepare($link, "SELECT `Organization_Name` FROM `organizations_info` WHERE `Organization_Name` LIKE ? LIMIT 0, 5");
mysqli_stmt_bind_param($stmt, "s", "%{$search_term}%");
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $organizaton_name);
while (mysqli_stmt_fetch($stmt)) {
}
Reference: mysqli SELECT With Prepared Statements
I searched the web for this function and found this. I copyed your source and got it working like this:
$search = "(SELECT Organization_Name FROM organizations_info WHERE Organization_Name LIKE '%". $search_term . "%' LIMIT 0, 5) ";
As you can see I changed the '%". $search_term . "%' , because you can't just place strings in sql query that is between "", you have to cut it in pieces, hope you understand now. I don't go on this site often, so it would be cool if you send me an mail if it fixed the problem to sceptdeckheroes#gmail.com, would like to hear from you, good luck.