Created
April 30, 2012 02:04
-
-
Save dwurf/2554894 to your computer and use it in GitHub Desktop.
PHP code sample for autocomplete with jquery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$connstring = "host=localhost dbname=test user=dwurf password=<secret>"; | |
$conn = pg_connect($connstring); | |
$search = ($_GET['term']); | |
if (!$conn) { die('Could not connect: ' . pg_last_error ());} | |
else | |
{ | |
$sql = "SELECT name FROM users_table WHERE name ILIKE '%$search%' ORDER BY name ASC"; | |
$result = pg_query($sql); | |
$json = '['; | |
$first = true; | |
while ($row = pg_fetch_array($result)) | |
{ | |
if (!$first) { $json .= ','; } else { $first = false; } | |
$json .= '{"value":"'.$row['name'].'"}'; | |
} | |
$json .= ']'; | |
echo $json; | |
exit(); | |
} | |
?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>Autocomplete test</title> | |
<script src="script/jquery.min.js"></script> | |
<script src="script/jquery-ui.min.js"></script> | |
<script language="javascript"> | |
$(document).ready(function() | |
{ | |
$('#auto').autocomplete( | |
{ | |
source: "./file.php", | |
minLength: 1 | |
}) | |
}) | |
</script> | |
</head> | |
<body> | |
<h1>Enter a name</h1> | |
<div class="ui-widget"> | |
<label for="auto">Name: </label> | |
<input id="auto" /> | |
</div> | |
<div class="ui-widget" style="margin-top:2em; font-family:Arial"> | |
Result: | |
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div> | |
</div> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DROP TABLE IF EXISTS users_table; | |
CREATE TABLE users_table ( | |
id serial NOT NULL, | |
name character varying(50) NOT NULL | |
); | |
INSERT INTO users_table VALUES (1, 'Steven'); | |
INSERT INTO users_table VALUES (2, 'Sally'); | |
INSERT INTO users_table VALUES (3, 'Reggie'); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment