Skip to content

Instantly share code, notes, and snippets.

@dwurf
Created April 30, 2012 02:04
Show Gist options
  • Save dwurf/2554894 to your computer and use it in GitHub Desktop.
Save dwurf/2554894 to your computer and use it in GitHub Desktop.
PHP code sample for autocomplete with jquery
<?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();
}
?>
<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>
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