jquery auto-suggestion example doesn't work - php

This might be very easy for some of you but very hard for me since first time doing it.
By looking at some examples on the web, I ended up with the code below for auto-suggestion example but the code doesn't work.
Thanks
HTML
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#textbox_postcode').autocomplete(
{
source: 'search-db.php',
minLength: 3
});
});
</script>
</head>
<body>
<form action="search.php" method="post">
<input type="text" id="textbox_postcode" value="" /> <input type="submit" value="Search" />
</form>
</body>
</html>
PHP
$keyword = ltrim(strtolower(strip_tags($_GET['keyword'])));
if (! $keyword) return;
$host =
'localhost'; $user = 'root'; $pswd = ''; $dtbs = 'geomaps';
$host_conn = mysql_connect($host, $user, $pswd); $dtbs_conn =
mysql_select_db($dtbs);
$return = array();
$sql = "SELECT id, postcode FROM postcodes WHERE postcode LIKE
'$keyword%' ORDER BY postcode"; $run = mysql_query($sql);
if (#mysql_num_rows($run) == 0) return;
while ($records = mysql_fetch_array($run, MYSQL_ASSOC)) { $return[] =
$records; }
echo json_encode($return);

Try changing $_GET['keyword'] to $_GET['term']

Related

Select multiple items from one dropdown and insert into multiple rows of database

I want to allocate multiple individual courses to students with one row per student-course combination when the data is coming from a multi-select (checkboxes) field on a form. That is, the data is returned as a single result with multiple courses, and I want to split this up.
Short version: the teacher selects multiple courses from a single dropdown but I want to save data in multiple rows.
Here is my code.
<?php
$con = mysqli_connect('localhost','root');
mysqli_select_db($con,'sss_qr');
$q="select * from course_tb ";
$result=mysqli_query($con,$q);
?>
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | Bootstrap Multi Select Dropdown with Checkboxes using Jquery in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css" />
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<h2 align="center">Bootstrap Multi Select Dropdown with Checkboxes using Jquery in PHP</h2>
<br /><br />
<form method="post" id="framework_form">
<div class="form-group">
<label>Select which Framework you have knowledge</label>
<select id="framework" name="framework[]" multiple class="form-control" >
<?php
if($result)
{
while($row=mysqli_fetch_array($result))
{
$course=$row["course_name"];
$code=$row["course_code"];
echo "<option value='$code'>$course</option>";
}
}
?>
</select>
</div>
<div class="form-group">
<input type="submit" class="btn btn-info" name="submit" value="Submit" />
</div>
</form>
<br />
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#framework').multiselect({
nonSelectedText: 'Select Framework',
enableFiltering: true,
enableCaseInsensitiveFiltering: true,
buttonWidth:'400px'
});
$('#framework_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data)
{
$('#framework option:selected').each(function(){
$(this).prop('selected', false);
});
$('#framework').multiselect('refresh');
alert(data);
}
});
});
});
</script>
and insert.php file
<?php
$connect = mysqli_connect("localhost", "root", "", "sss_qr");
if(isset($_POST["framework"]))
{
$framework = '';
foreach($_POST["framework"] as $row)
{
$framework .= $row . ', ';
}
$framework = substr($framework, 0, -2);
$query = "INSERT INTO allocoursestudent(course_code) VALUES('".$framework."')";
if(mysqli_query($connect, $query))
{
echo 'Data Inserted';
}
}
?>
so i solve the problem by using this code.
<?php
$con = mysqli_connect("localhost", "root", "", "sss_qr");
$course=$_POST['course'];
if($course)
{
foreach($course as $c)
{
$q="INSERT INTO allocoursestudent(course_code) VALUES('".$c."')";
mysqli_query($con,$q);
}
}
?>
Firstly, you need to create a new table that pairs the student and the courses.
Secondly, you need to display students in the form (dropdown menu).
After that, you can do something like this:
<?php
$connect = mysqli_connect("localhost", "root", "", "sss_qr");
if(isset($_POST["course_code"])){
$course_code = mysqli_real_escape_string($con, $_POST["course_code"]);
$student_id = mysqli_real_escape_string($con, $_POST["student_id"]);
$query = "INSERT INTO new_table_name(course_code, student_id) VALUES";
for($i=0; $i<count($course_code); $i++){
$query .= " ('".$course_code[$i] ."', '".$student_id[$i]."'),";
}
$query = substr($query, 0, -1);
if(mysqli_query($connect, $query)){
echo 'Data Inserted #'.$i;
}
}
?>

Insert And Retrieve Image from PostgreSQL bytea using PDO

Im working usign PDO and PHP.
This is my table in Postgre
CREATE TABLE public.img
(
id integer NOT NULL DEFAULT nextval('img_id_seq'::regclass),
nombre bytea
)
When i store the file data i use this method
<?php
$db = new PDO("pgsql:host=localhost;port=5432;dbname=sac;user=postgres;password=insertPass");
if(isset($_POST["insert"]))
{
$file = pg_escape_bytea(addslashes(file_get_contents($_FILES["image"]["tmp_name"])));
$sql = 'INSERT INTO img (nombre) VALUES (?)';
$ISp_Res = $db->prepare($sql);
$ISp_Res->bindParam(1, $file);
$ISp_Res->execute();
}
?>
And in the table the values are
ID nombre
4; "\377\330\377\340\\0\020JFIF\\0\001\001\\0\\0\001\\0\001\\0\\0\377\341\\0\234Exif\\0\\0II*\\0\010\\0\\0\\0\007\\0\\0\001\003\\0\001\\0\\0\\0S\002\\0\\0\001\001\003\\0\001\\0\\0\\0\026\002\\0\\0\022\001\003\\0\001\\0\\0\\0\\0\\0\\0\\02\001\002\\0\024\\0\\0\\ (...)"
And the form that i retrieve the values in my table
<?php
$query = "SELECT * FROM img ORDER BY id DESC";
$db = new PDO("pgsql:host=localhost;port=5432;dbname=sac;user=postgres;password=insertPass");
$result = $db->prepare($query);
$results = $result->execute();
$results = $result->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row) {
echo($row['nombre']);
$dat= pg_unescape_bytea($row['nombre']);
echo "<img src='".$dat."'";
}
?>
However when i try to retrieve the information i just get Resource id #2 and a Warning: pg_unescape_bytea() expects parameter 1 to be string
This is the testView
<script>
$(document).ready(function(){
$('#insert').click(function(){
var image_name = $('#image').val();
if(image_name == '')
{
alert("Please Select Image");
return false;
}
else
{
var extension = $('#image').val().split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
alert('Invalid Image File');
$('#image').val('');
return false;
}
}
});
});
</script>
<?php
$db = new PDO("pgsql:host=localhost;port=5432;dbname=sac;user=postgres;password=insertPass");
if(isset($_POST["insert"]))
{
$file = pg_escape_bytea(addslashes(file_get_contents($_FILES["image"]["tmp_name"])));
$sql = 'INSERT INTO img (nombre) VALUES (?)';
$ISp_Res = $db->prepare($sql);
$ISp_Res->bindParam(1, $file);
$ISp_Res->execute();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | Insert and Display Images From Mysql Database in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br /><br />
<div class="container" style="width:500px;">
<h3 align="center">Insert and Display Images From Mysql Database in PHP</h3>
<br />
<form method="post" enctype="multipart/form-data">
<input type="file" name="image" id="image" />
<br />
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-info" />
</form>
<br />
<br />
<table class="table table-bordered">
<tr>
<th>Image</th>
</tr>
<?php
$query = "SELECT * FROM img ORDER BY id DESC";
$db = new PDO("pgsql:host=localhost;port=5432;dbname=sac;user=postgres;password=insertPass");
$result = $db->prepare($query);
$results = $result->execute();
$results = $result->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row) {
echo($row['nombre']);
$dat= pg_unescape_bytea($row['nombre']);
echo "<img src='".$dat."'";
}
?>
</table>
</div>
</body>
</html>
Please tell me where im doing it wrong :(
Don't use addslashes() while inserting.
$target_file = '/path/to/file.jpg';
$img = fopen($target_file, 'r');
$data = fread($img, filesize($target_file));
$file = pg_escape_bytea($data);
While fetching data use
ob_start();
fpassthru($row['nombre']);
$dat= ob_get_contents();
ob_end_clean();
$dat= "data:image/*;base64," . base64_encode($dat);
echo "<img src='".$dat."'";

Ajax and SQL population of a dropdown

This seems to be the pain of my life I have now spent hours on this and none of the researched solutions seem to fix it. My code is supposed to populate a dropdown from a database called "notes" the field that is populated from is supposed is "name" and then the program is supposed to select all of the records with the name as the same selected. Except it does not seem to populate the list. I don't think that it's a database connection error as when all patients is selected all the records show up.
Here's my code:
<?php
// php select option value from database
$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "CareM_database";
// connect to mysql database
//load_data_select.php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
function fill_name($connect)
{
$output = '';
$sql = "SELECT name, id FROM name";
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row["id"].'">'.$row["name"].'</option>';
}
return $output;
}
function fill_patients($connect)
{
$output = '';
$sql = "SELECT * FROM notes";
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result))
{
$output .= '<div class="col-md-3">';
$output .= '<div style="border:1px solid #ccc; padding:20px; margin-bottom:20px;">'.$row["details"].'';
$output .= '</div>';
$output .= '</div>';
}
return $output;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Patient Notes View</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<br /><br />
<div class="container">
<h3>
<select name="name" id="name">
<option value="">Show All Patients</option>
<?php echo fill_patients($connect); ?>
</select>
<br /><br />
<div class="row" id="show_patients">
<?php echo fill_patients($connect);?>
</div>
</h3>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#name').change(function(){
var name_id = $(this).val();
$.ajax({
url:"load_data.php",
method:"POST",
data:{id:id},
success:function(data){
$('#show_name').html(data);
}
});
});
});
</script>
You are not calling fill_name function in your select, but calling fill_patients instead, And I don't see any element with the id of #show_name in your html.
<?php
// php select option value from database
$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "CareM_database";
// connect to mysql database
//load_data_select.php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
function fill_name($connect)
{
$output = '';
$sql = "SELECT name, id FROM name";
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row["id"].'">'.$row["name"].'</option>';
}
return $output;
}
function fill_patients($connect)
{
$output = '';
$sql = "SELECT * FROM notes";
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result))
{
$output .= '<div class="col-md-3">';
$output .= '<div style="border:1px solid #ccc; padding:20px; margin-bottom:20px;">'.$row["details"].'';
$output .= '</div>';
$output .= '</div>';
}
return $output;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Patient Notes View</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</script>
</head>
<body>
<br /><br />
<div class="container">
<h3>
<select name="name" id="name">
<option value="">Show All Patients</option>
<!-- <?php echo fill_patients($connect); ?> -->
<!-- call fill_name function instead of the above function -->
<?php echo fill_name($connect); ?>
</select>
<br /><br />
<div class="row" id="show_patients">
<?php echo fill_patients($connect);?>
</div>
</h3>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
$('#name').change(function(){
var name_id = $(this).val();
$.ajax({
url:"load_data.php",
method:"POST",
data:{id: name_id},
success:function(data){
$('#show_name').html(data);
}
});
});
});
</script>
</body>
</html>
Results
First of all add jquery.min.js before add bootstrap js

what is my mistake with PHP AJAX DB?

I want to get information from a database, and I want to put it in selectbox as option.
I tried to do it but I could not not put it what is my mistake?(db can connect I just delete server name )
I am not sure how I can put db rows in selectbox as option.
therefore, I think my code has a problem.
p.php
<?php
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM test" ;
$result = mysqli_query($conn, $sql) or die("Query: ($sql) [problem]");
$row = mysqli_fetch_assoc($result);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_row($result)) {
display("<option value=$row[seat_id]>",$row[seatnumber]."\n");
}
display ("</select>", "\n");
} else {
echo "0 results";
}
mysqli_close($conn);
function display($tag , $value) {
echo $tag . $value ;
}
?>
p.html
<html>
<head>
<meta charset="utf-8">
<link href="" rel="stylesheet" type="text/css" />
</head>
<script type="text/javascript">
function transfer(){
var pix = document.getElementById('pix').value;
document.abc.test.value =pix;
}
</script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
</script>
<script>
function ajaxWay() {
// syntax: $.post(URL,data,callback);
$.get("p.php", function(dataFromtheServer) {
$("#result").html(dataFromtheServer);
});
}
</script>
<body>
<div id="a" style="text-align:center;">
<form name="abc" method="get" action="p.php">
<select id='pix' onchange='ajaxWay()'>
<input type="button" value="click" onclick="transfer();">
<input type="text" name="test" id="test">
</form>
</div>
</body>
</html>
If your main problem is that you are not able to embed options into your HTML, try something like this:
<html>
<head>
<meta charset="utf-8">
<link href="" rel="stylesheet" type="text/css" />
</head>
<script type="text/javascript">
function transfer(){
var pix = document.getElementById('pix').value;
document.abc.test.value =pix;
}
</script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
</script>
<script>
function ajaxWay() {
// syntax: $.post(URL,data,callback);
$.get("prefinal.php", function(dataFromtheServer) {
$("#result").html(dataFromtheServer);
});
}
</script>
<body>
<div id="a" style="text-align:center;">
<form name="abc" method="get" action="p.php">
<?php
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM test" ;
$result = mysqli_query($conn, $sql) or die("Query: ($sql) [problem]");
?>
<select id='pix' onchange='ajaxWay()'>
<?php
$row = mysqli_fetch_assoc($result);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_row($result))
{
echo '<option value="' . $row[0] . ">' . $row[0] . '</option>';
}
}
mysqli_close($conn);
?>
</select>
<input type="button" value="click" onclick="transfer();">
<input type="text" name="test" id="test">
</form>
</div>
</body>
</html>
Note that in the above I am using your code from p.php to generate the actual content for the select options. The form should NOT submit to p.php, but to some other script that will process the form and perform the required actions. I would help more if I knew more about what you were trying to achieve!

Feeding JQuery autocomplete from mysql database

I am trying to create an autocomplete field using JQuery, which receives its autocompletions from a mysql database.
Index.php:
<!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/themes/base/jquery-ui.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/vendor/modernizr-2.6.2.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.2.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
<script type="text/javascript">
$(function() {
$("#college").autocomplete({
source: "search.php",
minLength: 2
});
});
</script>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<fieldset>
<legend>jQuery UI Autocomplete Example - PHP Backend</legend>
<label for="state">State (abbreviation in separate field): </label>
<input type="text" id="college" name="college" />
<input type="submit" name="submitBtn" value="Submit" />
</fieldset>
</form>
<?php
if (isset($_POST['submit'])) {
echo "<p>";
while (list($key,$value) = each($_POST)){
echo "<strong>" . $key . "</strong> = ".$value."<br />";
}
echo "</p>";
}
?>
<!--[if lt IE 7]>
<p class="chromeframe">You are using an <strong>outdated</strong> browser. Please upgrade your browser or activate Google Chrome Frame to improve your experience.</p>
<![endif]-->
<!-- Add your site or application content here -->
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
</script>
</body>
</html>
search.php:
/* Connection vars here for example only. Consider a more secure method. */
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'college';
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
$return_arr = array();
if ($conn)
{
$ac_term = "%".$_GET['term']."%";
$query = "SELECT * FROM college_list where name like :term";
$result = $conn->prepare($query);
$result->bindValue(":term",$ac_term);
$result->execute();
/* Retrieve and store in array the results of the query.*/
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$row_array['name'] = $row['name'];
array_push($return_arr,$row_array);
}
}
/* Free connection resources. */
//$conn = null;
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
?>
It's currently retrieving correctly from the database, because it's getting the correct number of autocompletions. However, they're all blank. It appears to not actually be feeding "name" back into the field and I can't seem to figure out why. Any ideas?
Without seeing the autocomplete code you are using, I would say that you need a 1-dimensional array instead of a 2-dimensional one as you are generating now.
You could try changing:
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$row_array['name'] = $row['name'];
array_push($return_arr,$row_array);
}
To:
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
array_push($return_arr, $row['name']);
}
edit: check the api documentation, you need to build your array differently, something like:
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
array_push($return_arr, array('label' => $row['name'], 'value' => $row['name']));
}

Categories