I am attempting a bit of ajax for the first time. I'm trying to write a live search where on every character entered a search of a MySQL database is run.
This is my code so far:
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<script type="text/javascript">
function getStates(value){
$.post(
"getstates.php",
{partialState:value},
function(data){
$("#results").html(data);
});
}
</script>
</head>
<body>
<input type="text" name="input" onkeyup="getStates(this.value)" /><br />
<div id="results"></div>
</body>
</html>
getStates.php
//test the connection
try{
//connect to the database
$dbh = new PDO("mysql:host=127.0.0.1;dbname=livesearch","root", "usbw");
//if there is an error catch it here
} catch( PDOException $e ) {
//display the error
echo $e->getMessage();
}
$partialState = $_POST['partialState'];
$query = $dbh->prepare("SELECT state_name FROM tbl_state WHERE state_name LIKE '%$partialSate%'");
$query->execute();
$result = $query->fetchAll();
foreach($result AS $state){
echo '<div>'.$state['state_name'].'</div>';
}
The mySQL database is constructed correctly using the correct table names etc.
Why is it not returning the resulting states from the database?
The problem is that you have made a typo in your query:
$query = $dbh->prepare("SELECT state_name
FROM tbl_state
WHERE state_name
LIKE '%$partialSate%'");
^^^^Missing t
Should be
$query = $dbh->prepare("SELECT state_name
FROM tbl_state
WHERE state_name
LIKE '%$partialState%'");
But you should also use prepared query's correctly:
Fixed code:
<?php
if(isset($_POST['partialState'])){
//test the connection
try{
//connect to the database
$dbh = new PDO("mysql:host=127.0.0.1;dbname=livesearch","root", "usbw");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
//if there is an error catch it here
} catch( PDOException $e ) {
//display the error
echo $e->getMessage();
}
$query = $dbh->prepare("SELECT state_name
FROM tbl_state
WHERE state_name
LIKE :like");
$query->execute(array(':like'=>'%'.$_POST['partialState'].'%'));
$result = $query->fetchAll();
foreach($result AS $state){
echo '<div>'.$state['state_name'].'</div>';
}
die();
}
?>
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
function getStates(value){
$.post("index.php", { "partialState":value },
function(data){
$("#results").html(data);
});
}
</script>
</head>
<body>
<input type="text" name="input" onkeyup="getStates(this.value)" /><br />
<div id="results"></div>
</body>
</html>
Related
Hello I have been building a shout box and i am so close - i just cant get the fetched data to refresh on input.
the fetched data refreshes on interval but when i press submit i have to wait for it to refresh by that interval i would like it to be instant on submit
sql
CREATE TABLE IF NOT EXISTS `shoutbox` (
`msgid` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`message` text DEFAULT NULL,
PRIMARY KEY (`msgid`)
) ENGINE=MyISAM;
index.php
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap 5 Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<p id="shoutbox"></p>
<form id='contactForm1' name='contactForm1' action='postshout.php' method='post'>
<div class="row">
<div class="col-md-12">
<input id="message" class="form-control shoutbox_msgbox" type='text' size='100%' name="message">
</div>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var frm = $('#contactForm1');
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log('Submission was successful.');
console.log(data);
},
complete: function(){
$("#message").focus().val('');
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
});
</script>
<script>
function updateShouts(){
// always refresh #shoutbox
$('#shoutbox').load('getshout.php');
}
setInterval( "updateShouts()", 15000 );
updateShouts();
</script>
</body>
</html>
getshout.php
<?php
$servername = "localhost";
$username = "dbusername";
$password = "dbpassword";
try {
$conn = new PDO("mysql:host=$servername;dbname=dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$sth = $conn->prepare("SELECT * FROM shoutbox ORDER BY `msgid` DESC");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
$result = $sth->fetchAll();
foreach ($result as $row) {
echo "$row[message]<br>";
}
postshout.php
<?php
$servername = "localhost";
$username = "dbusername";
$password = "dbpassword";
try {
$conn = new PDO("mysql:host=$servername;dbname=dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$data = [
'message' => $_POST['message'],
];
$sql = "INSERT INTO shoutbox (message) VALUES (:message)";
$stmt= $conn->prepare($sql);
$stmt->execute($data);
I am developing a simple jquery autocomplete using php. It works just fine for the most part... but when I do certain searches, it does not detect specific entries. For example, when I search for "Si" I get a list including "Simon", but when I search for "Jo" there is nothing.
Here are the two files I have:
index.php
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Search</title>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" />
</head>
<body>
<form action='' method='post'>
<p><label>Name:</label><input type='text' name='Name' value='' class='auto'></p>
</form>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
$(function() {
//autocomplete
$(".auto").autocomplete({
source: "search.php",
minLength: 2
});
});
</script>
</body>
</html>
search.php
<?php
define('DB_SERVER', 'localhost');
define('DB_USER', 'xxx');
define('DB_PASSWORD', 'xxx');
define('DB_NAME', 'xxx');
if (isset($_GET['term'])){
$return_arr = array();
try {
$conn = new PDO("mysql:host=".DB_SERVER.";port=8889;dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT Name FROM People WHERE Name LIKE :term');
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
while($row = $stmt->fetch()) {
$return_arr[] = $row['Name'];
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
/* Return results as json encoded array. */
echo json_encode($return_arr);
}
?>
Might this have something to do with an exception list? Or have I made an error with the code?
As a newbie I am in awe of the great help from this site!
Help me please.. it show "select_modelcar.php?brandid=undefined" when i choose select form but i try to paste this code in url and define id "select_modelcar.php?brandid=40", have the results. i want to choose same categories in select form such as when i choose brand "Toyota", it'll show all car model in Toyota brand (Camry, Yaris, etc.).
when i click select form >>
enter image description here
past in url and define id >>
enter image description here
select_brandcar.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>
<?php $servername = "localhost";
$username = "root";
$password = "usbw";
mysql_connect($servername,$username,$password);
mysql_select_db("carspecth");
?>
<body>
<script>
function ValueID(){
document.getElementById("getval").innerHTML = ('select_modelcar.php?brandid='+this.value);;
};
</script>
<select name="select_brandcar" id="select_brandcar" onclick="ValueID();" >
<option>Press Choose</option>
<?php
$sql = sprintf ("SELECT * FROM brand" );
$res = mysql_query ($sql);
while ($arr = mysql_fetch_array($res)){
printf ("<option value='%s'>%s</option>" ,$arr['brandid'], $arr['brandname']);
}
?>
<span id="getval"></span>
</body>
</html>
select_modelcar.php
<?php
mysql_query("SET NAMES UTF8");
include 'include_connectdb.php';
#$varbrandid = $_GET['brandid'];
#$sql = sprintf("SELECT * FROM maingeneration WHERE brandfk = %s", $varbrandid);
/*id ของตาราง catagory*/
#$res = mysql_query($sql);
printf("<select name='select' id='select'>");
while ($arr = mysql_fetch_array($res)) {
printf("<option value='%s'>%s</option>", $arr['maingenerationid'], $arr['maingenerationname']);
}
printf("</select>");
?>
Thank you...........!
Please use onchange event instead of onclick and pass the value in the ValueID function.
Please replace javascript and php code with this:
<script>
function ValueID(vid){
$.ajax({
url: 'select_modelcar.php?brandid='+vid,
type: 'POST',
success: function (data) {
if (data === 'success') {
document.getElementById("getval").innerHTML = data;
}
}
});
};
</script>
<select name="select_brandcar" id="select_brandcar" onchange="ValueID(this.value);" >
<option>Press Choose</option>
<?php
$sql = sprintf ("SELECT * FROM brand" );
$res = mysql_query ($sql);
while ($arr = mysql_fetch_array($res)){
printf ("<option value='%s'>%s</option>" ,$arr['id'], $arr['name']);
}
?>
<span id="getval"></span>
In PHP FIle:
<?php
mysql_query("SET NAMES UTF8");
include 'include_connectdb.php';
#$varbrandid = $_GET['brandid'];
#$sql = sprintf("SELECT * FROM maingeneration WHERE brandfk = %s", $varbrandid);
/*id ของตาราง catagory*/
#$res = mysql_query($sql);
$select = "<select name='select' id='select'>");
while ($arr = mysql_fetch_array($res)) {
$select .= printf("<option value='%s'>%s</option>", $arr['maingenerationid'], $arr['maingenerationname']);
}
$select .="</select>";
echo $select;
exit;
?>
Try this out:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>
<?php $servername = "localhost";
$username = "root";
$password = "usbw";
mysql_connect($servername,$username,$password);
mysql_select_db("carspecth");
?>
<body>
<script>
function ValueID(element){
document.getElementById("getval").innerHTML = ('select_modelcar.php?brandid='+element.value);;
};
</script>
<select name="select_brandcar" id="select_brandcar" onclick="ValueID(this);" >
<option>Press Choose</option>
<?php
$sql = sprintf ("SELECT * FROM brand" );
$res = mysql_query ($sql);
while ($arr = mysql_fetch_array($res)){
printf ("<option value='%s'>%s</option>" ,$arr['brandid'], $arr['brandname']);
}
?>
</select>
<span id="getval"></span>
</body>
</html>
so I am trying to display multiple results from a database when a query is searched, the query is passed from a search box on another page.
I have it displaying one result, but that is all it will display.
I need it to display all the results that are relevant to the search query.
the php code is below
<meta charset="UTF-8">
<?php
$mysqli = new mysqli('localhost', 'scott', 'tiger','courses');
if ($mysqli->connect_errno)
{
die('Database connection failed');
}
//$m->set_charset('utf8');
$search_sql = "
SELECT title, summary, id
FROM course
WHERE title LIKE '%".$_POST['searchBar']."%'";
$result = $mysqli->query($search_sql) or die($mysqli->error);
$search_result = $result->fetch_assoc();
?>
<!doctype html>
<head>
<meta charset="utf-8">
<h1>Search Results</h1>
</head>
<body>
<h3><?= $search_result['title'] ?></h1>
<p><?= $search_result['summary'] ?></p>
</body>
and the code for the search bar
<!doctype html>
<html>
<Head>
<meta charset = "utf-8">
<title>Search</title>
</head>
<body>
<h2>Search</h2>
<form name="search" method="post" action="SearchResultsPage.php">
<input name="searchBar" type="text" size="40" maxlength="60" />
<input type="submit" name="Submitsearch" value="Search" />
</form>
</body>
Does anyone have any suggestions?
Thanks in advance;
You will need to place it in a while loop to show multiple results, the fetch function you're using will only retrieve one row, if you place it in a loop you can keep fetching until there is nothing to fetch:
//$m->set_charset('utf8');
$search_sql = "
SELECT title, summary, id
FROM course
WHERE title LIKE '%".$_POST['searchBar']."%'";
$result = $mysqli->query($search_sql) or die($mysqli->error);
?>
<!doctype html>
<head>
<meta charset="utf-8">
<h1>Search Results</h1>
</head>
<body>
<?PHP while($search_result = $result->fetch_assoc()) { ?>
<h1><?= $search_result['title'] ?></h1>
<p><?= $search_result['summary'] ?></p>
<?PHP } ?>
</body>
P.S. your code is vulnerable to SQL injection, you should read about prepared statements. More Info on that
You can iterate over your query results with a while loop. To complete the example I added the necessary data cleaning.
<?php
// function to clean post data
function cleanPost(&$value) {
if (is_array($value)) {
foreach ($value as $k => $v) {
$value[$k] = cleanPost($v);
}
return $value;
}
else {
$value = mysql_real_escape_string($value);
return trim(htmlentities(strip_tags($value)));
}
}
// search function
function search() {
// check if post data is set
if (isset($_POST['searchBar'])) {
// make link with db
$link = mysqli_connect('localhost', 'scott', 'tiger','courses');
if (!$link)
return false;
}
// clean your post data
$cleanPostData = cleanPost($_POST);
// query
$sql = "SELECT title, summary, id FROM course WHERE title LIKE '%".$cleanPostData['searchBar']."%'";
$result = mysqli_query($link, $sql);
// iterate over results
if (isset($result) && mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
// here is your data
echo $row['title'] . "< br/>";
echo $row['summary'] . "< br/>";
echo $row['id'] . "< br/>";
}
}
}
}
// call search function
search();
?>
I need some help I am trying to create a PHP form using sqlite3 and I keep on getting a "syntax error, unexpected T_CATCH in post.php on line 10". All I want to do from the php form is update an existing sqlite3 database in the table1 where the column type = p and the column id = 340 with the values from the form.
HTML Code:
<html>
<head>
<title>Update Form</title>
</head>
<body style="font-size:12;font-family:verdana">
<form action="post.php" method="post">
<p>
Slot1: <input type="text" name="slot1"><br>
Slot2: <input type="text" name="slot2"><br>
</p>
<p>
<input type="submit" name="update" value="update">
</p>
</form>
</body>
</html>
PHP Code: Post.php
<?php
$slot1 = sqlite_escape_string($_POST['slot1']);
$slot2 = sqlite_escape_string($_POST['slot2']);
try
{
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
catch(Exception $e)
{
echo $e->getMessage();
}
}
if (!empty($slot1)) {
try
{
$stmt = $db->prepare("UPDATE tabel1 SET Slot1Pos = :slot1, Slot2Pos = :slot2 WHERE Type = P and ID = 340");
$stmt->bindParam(':slot1', $slot1, PDO::PARAM_STR);
$stmt->bindParam(':slot2', $slot2, PDO::PARAM_STR);
$stmt->execute()
}
catch(Exception $e)
{
echo $e->getMessage();
}
echo "Form submitted successfully";
}
Looks like you're missing a brace:
try {
$db = new PDO("sqlite:DefaultLibrary.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(Exception $e) {
echo $e->getMessage();
}