Autocomplete dynamic search SQL database from PHP - javascript

I have a search box where search is done through database. In the code I have, the search is done in one input box and the dynamic search output is shown in a text area below it.
What I want is a search like Google, where when the user stars typing, it should show similar items from the db table.
For example, if I have two organizations named "Dummy 1" and "Dummy 2" and the user types in "du", the search bar should show the 2 results and user should be able to select one.
The code I have is:
<form action="newbrand.php" method="post">
<br>
Brand Name: <input type="text" name="bname" /><br><br>
Search for an Organization: <input type="text" name="search" onkeyup="searchq()" id="output"><
Selected Organization:<textarea id="output"></textarea>
</form>
The js is like this:
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output){
$("#output").html(output);
}
}
</script>
This is the search.php file:
<?php
include 'db_connect.php';
$link = mysqli_connect($host, $username, $password, $db);
if(!link){
echo "DB Connection error";
}
$output = '' ;
$output2 = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
//$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%$searchq%'")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<div>No results!</div>';
}else{
while($row = mysqli_fetch_array($query)){
$orgname = $row['Organisation_Name'];
$orgid = $row['Organisation_Id'];
$subs = $row['Subscription_Type'];
//$output = echo "<option value='".$orgname."'>" . $orgname . "</option>";
$output = $orgname;
$output2 = $orgid;
$output3 = $subs;
//$output = '<div>'.$orgname.'</div>';
}
}
}
echo ($output);
?>
How can I achieve that?

In the JS code...
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output){
$("#output").html(output);
}
}
</script>
you have given the id(#output) of a input type element to display(or to return) the HTML statements and the js script also not closed properly (syntax error).So the valid statement will be...
<form action="newbrand.php" method="post">
<br>
Brand Name: <input type="text" name="bname" /><br><br>
Search for an Organization: <input type="text" name="search" onkeyup="searchq()" id="output"><
Selected Organization:<textarea id="output"></textarea>
</form>
<br>
<div id="mydiv"></div>
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output){
$("#mydiv").html(output);
});
}
</script>

Just change your query :
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%".$searchq."%' ")or die("Could not search!");
And the query will work fine :)
Then output the response in HTML in your search.php (manage the css accordingly) :
<?php
include 'db_connect.php';
$link = mysqli_connect($host, $username, $password, $db);
if(!link){
echo "DB Connection error";
}
$output = '' ;
$output2 = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
//$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%".$searchq."%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<div>No results!</div>';
}else{
while($row = mysqli_fetch_array($query)){
$orgname = $row['Organisation_Name'];
$orgid = $row['Organisation_Id'];
$subs = $row['Subscription_Type'];
?>
<div><?php echo $orgname; ?></div>';
<div><?php echo $orgid ; ?></div>';
<div><?php echo $subs ; ?></div>';
<?php
} // while
} // else
} // main if
?>
I hope this is what you required !!

Related

An issue when passing a PHP parameter to a JavaScript function

I the following code, I have a form that consists of three fields and two buttons. In the Review button, I would like to show any word in Arabic randomly and let the user show its translation in English by ticking the Show translation button.
<html>
<body>
<script>
function myFun1(var) {
document.getElementById("demo").innerHTML = "The translation in English is " + var;
}
</script>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$english = $_POST["english"];
$arabic = $_POST["arabic"];
$example = $_POST["example"];
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<textarea name="english" rows="4" cols="70" placeholder="English">English</textarea>
<br>
<textarea name="arabic" rows="4" cols="70" placeholder="Arabic">Arabic</textarea>
<br>
<textarea name="example" rows="4" cols="70" placeholder="Example">Example</textarea>
<br><br>
<input type="submit" name="add" value="Add new">
<input type="submit" name="review" value="Review">
<br>
<p id="demo"></p>
</form>
<?php
$servername = "localhost";
$username = "xxx";
$password = "yyy";
$dbname = "vdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['add'])) {
$sql = "INSERT INTO Vocabulary (English, Arabic, Example)
VALUES ('$english', '$arabic', '$example')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
elseif (isset($_POST['review'])) {
$sql = "SELECT COUNT(ID) as total FROM Vocabulary";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
#echo $row['total'];
$generated = rand(1,$row['total']);
$sql1 = "SELECT * FROM Vocabulary where ID = $generated";
$result1 = $conn->query($sql1);
$row1 = $result1->fetch_assoc();
echo "<br>";
echo $row1['Arabic'];
echo "<br><br>";
$eng = $row1['English'];
echo '<button onClick = "myFun('.$eng.')">Show translation</button>';
}
$conn->close();
?>
</body>
</html>
In the code, the following line creates the button and trigger the myFun1() function:
echo '<button onClick = "myFun('.$eng.')">Show translation</button>';
The problem is when the button is clicked, nothing happens (the message is not shown at all). Any ideas how to fix it?
Firstly change the argument var to some another argument name as var is a keyword in javascript
<script type="text/javascript">
function myFun(as) {
document.getElementById("demo").innerHTML = "The translation in English is " + as;
}
</script>
Secondly, you have to pass the string value in single or double quotes for that use inverted slash \ and rectify the function name from myFun() to myFun1()
echo '<button onClick = "myFun1(\''.$eng.'\')">Show translation</button>';
Rest your code is perfect.
You have definition of function myFun1(var), but you are calling myFun(). I guess this is the problem why there is nothing after clicking on button.
Add this to the top before
< html > tag
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$english = $_POST["english"];
$arabic = $_POST["arabic"];
$example = $_POST["example"];
}
?>

Display data in dropdown lists from another file (php,mysql,javascript)

I got multiple database dropdown lists with javascript, and I want to display result in dropdown menu. But at this moment, nothing shows. It shows Regions (drop down menu), but dosn't show Countries (drop down menu)
My Core Code(I want to display result in Country drop down menu):
<html>
<body>
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function abc(){
var e = document.getElementById("Region_ID");
var val = e.options[e.selectedIndex].value;
$.post("getSecondDropDown.php",{ Region_ID:val}, function( data ) {
$("#Country_ID").html(data);
});
}
</script>
<form action="/NewService.php" id="ServiceForm" method="post">
Name:<input type="text" name="Service_Name"></br>
Region: <select name="Region_ID" id="Region_ID" onchange="abc()" form="ServiceForm">
<?php
include('config.php');
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT Region_ID, Region_Name FROM Regions");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt as $v) {
echo "<option value='" . $v['Region_ID'] ."'>" . $v['Region_Name'] ."</option>";
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
</select></br>
Country: <select name="Country_ID" form="ServiceForm">
<script>document.write($("#Country_ID"))</script>
</select></br>
<input type="submit">
</form>
</body>
</html>
Second php file(getSecondDropDownMenu.php):
<?php
$Region_ID =$_POST['Region_ID'];
$option="";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT Country_ID, Country_Name FROM Countries WHERE Region_ID ='$Region_ID'");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt as $v) {
echo "<option value='" . $v['Country_ID'] ."'>" . $v['Country_Name'] ."</option>";
}
echo $option;
?>
I Think that problem is here, but don't really know it :
Country: <select name="Country_ID" form="ServiceForm">
<script>document.write($("#Country_ID"))</script>
</select></br>
In the second file ( getSecondDropDownMenu ) you need to create a function
<?php
function functionName(){
$Region_ID =$_POST['Region_ID'];
$option[] = null;
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT Country_ID, Country_Name FROM Countries WHERE Region_ID ='$Region_ID'");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt as $v) {
array_push($option, "<option value='" . $v['Country_ID'] ."'>" . $v['Country_Name'] ."</option>");
}
return option;
}
?>
Then in the other file the first one include it
include('getSecondDropDownMenu.php');
and do
$arrayForSecondDropdown[] = functionName();
and then do the foreach like
foreach($arrayForSecondDropdown as $v){
echo $v;
}
You can simplify the abc function by calling it with onchange='abc(this.value)' and the target dropdown requires an ID attribute to enable the callback to add the html data. Also, as you are not passing any variables to the sql statement you do not really require the prepared statement, a simple query should suffice.
<html>
<head>
<title>dependant select menu</title>
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function abc( value ){
$.post("getSecondDropDown.php",{ Region_ID:value }, function( data ) {
$("#Country_ID").html( data );
}
);
}
</script>
</head>
<body>
<form action="/NewService.php" id="ServiceForm" method="post">
Name:<input type="text" name="Service_Name"></br>
Region: <select name="Region_ID" id="Region_ID" onchange="abc( this.value )" form="ServiceForm">
<?php
include('config.php');
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $conn->prepare( "SELECT Region_ID, Region_Name FROM Regions" );
$stmt->execute();
$result = $stmt->setFetchMode( PDO::FETCH_ASSOC );
foreach($stmt as $v) {
echo "<option value='" . $v['Region_ID'] ."'>" . $v['Region_Name'] ."</option>";
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
</select>
</br>
Country: <select id='Country_ID' name="Country_ID" form="ServiceForm"></select>
</br>
<input type="submit">
</form>
</body>
</html>
I think your missed the config file to include in your Second php file(getSecondDropDownMenu.php):. So the scripts in this is not able to run. Why this happens means this page is able to get database connection .ou are fetching the country list from database on the basis of region so here no database connection is achieved.So please include config.php and try again.And also you have done another mistake in concatenation of php variable with the string .IE in the country fetching query you should concatenate the region variable with correct syntax.Please see the below code.
Second php file(getSecondDropDownMenu.php):
<?php
include('config.php');
$Region_ID =$_POST['Region_ID'];
$option="";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT Country_ID, Country_Name FROM Countries WHERE Region_ID ='".$Region_ID."'");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt as $v) {
echo "<option value='" . $v['Country_ID'] ."'>" . $v['Country_Name'] ."</option>";
}
echo $option;
?>
I think this may help you.
You have written the code to display with the help of ID for the select tag but you have not been given any ID for the select tag
<script>document.write($("#Country_ID"))</script>
As per the script you have provided you have to add an ID Attribute for the select tag.
I would recommend not using document.write, especially after the page has loaded. It can lead to unexpected results. Just use this method:
Try Replacing with this:
document.getElementById('Country_ID').innerHTML = "something important";
If however, you are not willing to replace the whole innerHTML, you could append something to it:
document.getElementById('Country_ID').insertAdjacentHTML('beforeend', "something added");

MySQL query keeps failing. page is not redirecting

I have this simple insert query that basically add one row to the db table. but it is not only adding the row but its not redirecting neither. i tried redirecting through javaScript, it gets redirected but still not adding the row. the page is live at:
http://arj-profile.com/public/new_subject.php
(when you go the link click on about widget and then click on add a subject.
i was originally trying this on mamp and i have tried turning on output buffering on php.ini too, still no luck.
any help appreciated. if you need additional information just console log on the above link or let me know i can provide it my entire tables and db as well.
the form page has the following code:
<!-- including functions -->
<?php include("../includes/db_connect.php") ?>
<?php require_once("../includes/functions.php"); ?>
<!-- query -->
<!-- end of query -->
<!-- including header -->
<?php include("../includes/header.php") ?>
<?php find_selected_page();?>
<div class="container-fluid">
<div class="row">
<!-- menu -->
<div class="col-md-3 sidebar">
<?php echo navigation(); ?>
</div>
<!-- body -->
<div class="col-md-9 body">
<form action="create_subject.php" method="post">
<p>Subject name:
<input type="text" name="menu_name" value=""/>
<p>
<p>Position
<select name="position">
<?php
$subject_set = find_all_subjects();
$subject_count = mysqli_num_rows ($subject_set);
for ($count = 1; $count <= ($subject_count + 1); $count++){
echo "<option value=\"{$count}\">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0" />No
&nbsp
<input type="radio" name="visible" value="1" />Yes
</p>
<input type="submit" name="submit" value="Submit">
</p>
<br />
<!-- redirect -->
Cancel
</form>
</div>
</div>
</div>
<!-- footer -->
<?php include("../includes/footer.php") ?>
please try adding but filling out the form, as you see it goes to the following page which actually contains the query but it is not supposed to go there, it should just redirect back to the create_subject.php.
<?php include("../includes/db_connect.php") ?>
<?php require_once("../includes/functions.php"); ?>
<?php
if (isset($_POST['submit'])){
$menu_name = mysqli_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$menu_name = mysqli_prep($menu_name);
$query = "insert into subjects(";
$query = " menu_name, position, visible";
$query = ") values (";
$query = " '{$menu_name}', {$position}, {$visible}";
$query = ")";
$result = mysqli_query($connection, $query);
if ($result){
$msg = "Subject created";
redirect_to("manage_subject.php");
}
}else {
$msg = "Subject creation failed";
redirect_to("new_subject.php");
}
?>
<?php
if (isset($connection)){mysqli_close($connection); }
?>
in my function.php i have:
<?php
function redirect_to($new_location){
header("Location: " . $new_location);
exit;
}
function mysqli_prep($string){
global $connection;
$escape_string = mysqli_real_escape_string($cnnection, $string);
return $escape_string;
}
function confirm_query($result_set){
if (!$result_set){
die("DB Query Failed");
}
}
function find_all_subjects(){
global $connection;
$query = "select * ";
$query .= "from subjects ";
$query .= "where visible = 1 ";
$query .= "order by position asc";
$subject_set = mysqli_query($connection, $query);
confirm_query($subject_set);
return $subject_set;
}
function find_pages_for_subjects($subject_id){
global $connection;
$safe_subject_id = mysqli_real_escape_string($connection, $subject_id);
$query = "select * ";
$query .= "from pages ";
$query .= "where visible = 1 ";
// an aditional line to relate pages to the subject, subject_id is what rlate two tables together
// dont forget space between lines
$query .= "AND subject_id = {$safe_subject_id} ";
$query .= "order by position asc";
$page_set = mysqli_query($connection, $query);
// the result captured can not be used twice for two different queries
// so result varibale should have unique names
confirm_query($page_set);
return $page_set;
}
function find_subject_by_id($subject_id){
global $connection;
$safe_subject_id = mysqli_real_escape_string($connection, $subject_id);
$query = "select * ";
$query .= "from subjects ";
$query .= "where id = {$safe_subject_id} ";
$query .= "limit 1";
$subject_set = mysqli_query($connection, $query);
confirm_query($subject_set);
if ($subject = mysqli_fetch_assoc($subject_set)){
return $subject;
}else {
return null;
}
}
function find_page_by_id($page_id){
global $connection;
$safe_page_id = mysqli_real_escape_string($connection, $page_id);
$query = "select * ";
$query .= "from pages ";
$query .= "where id = {$safe_page_id} ";
$query .= "limit 1";
$page_set = mysqli_query($connection, $query);
confirm_query($page_set);
if ($page = mysqli_fetch_assoc($page_set)){
return $page;
}else {
return null;
}
}
function find_selected_page(){
global $current_subject;
global $current_page;
if (isset($_GET["subject"])){
$current_subject = find_subject_by_id($_GET["subject"]);
$current_page = null;
} elseif (isset($_GET["page"])){
$current_page = find_page_by_id($_GET["page"]);
$current_subject = null;
} else{
$current_subject = null;
$current_page = null;
}
}
function navigation(){
$output = "<ul>";
$subject_set = find_all_subjects();
while($subject = mysqli_fetch_assoc($subject_set)){
$output .= "<li><a href=\"manage-content.php?subject=";
$output .= urlencode($subject["id"]);
$output .= "\">";
$output .= $subject["menu_name"];
$output .= "</a>";
$page_set = find_pages_for_subjects($subject["id"]);
$output .= "<ul>";
while($page = mysqli_fetch_assoc($page_set)){
$output .= "<li><a href=\"manage-content.php?page=";
$output .= urlencode($page["id"]);
$output .= "\">";
$output .= $page["menu_name"];
$output .= "</a></li>";
}
mysqli_free_result($page_set);
$output .= "</ul></li>";
}
mysqli_free_result($subject_set);
$output .= "</ul>";
return $output;
}
?>
function mysqli_prep( $string ){
global $connection;
return mysqli_real_escape_string( $connection, $string );
}
<?php include("../includes/db_connect.php") ?>
<?php require_once("../includes/functions.php"); ?>
<?php
$redir='new_subject.php';
if ( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['submit'] ) ){
$menu_name = mysqli_prep( $_POST["menu_name"] );
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$query = "insert into subjects
( menu_name, position, visible )
values
( '{$menu_name}', {$position}, {$visible} )";
$result = mysqli_query( $connection, $query );
if ( $connection ) mysqli_close( $connection );
if( $result ) $redir='manage_subject.php';
}
redirect_to( $redir );
?>

Combine input box and select box to create a search bar

I have an input box that serves as a search box, and I populate a select box by querying a SQL database. For example, there are two organizations called "Dummy Organization" and "Dummy 2" in my db. So when the user starts typing "du", the select box fills with those two organizations. What I want to do is to combine these two fields: the input box (that acts as the search box) and the select box (which displays the results). My research shows that selectize.js can be useful, but since I'm new to js, I can't figure out how. Can someone please help me? My code is as below:
js that gets the data from the db:
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output4){
$("#output4").html(output4);
}
</script>
The form:
<form action="newbrand.php" method="post" id="form">
<br>
Brand Name: <input type="text" name="bname" required /><br><br>
Search for an Organization: <input type="text" required name="search" onkeyup="searchq()" id="output"><br><br>
Selected Organization:
<select id="output4" name="taskOption"></select>
</form>
The search.php file
<?php
include 'db_connect.php';
$link = mysqli_connect($host, $username, $password, $db);
if(!link){
echo "DB Connection error";
}
$output = '' ;
$output2 = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
//$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%".$searchq."%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<option>No results!</option>';
}else{
while($row = mysqli_fetch_array($query)){
$orgname = $row['Organisation_Name'];
$orgid = $row['Organisation_Id'];
$subs = $row['Subscription_Type'];
?>
<option value="<?php echo $orgid; ?>"><?php echo $orgname; ?></option>
<div><?php echo $subs; ?></div>
<?php
} // while
} // else
} // main if
?>

How to Select one of the same name values in one column via input type and then submit button?

What Im trying to do is put one name into a input type box and press submit, once submitted Id like it only to show all the same name rows and NOT all names in database? Can anyone help as I'm trying out or || in the PHP but only getting all results?
<form method="post" action="">
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
<button onclick="refreshMap()">Refresh</button>
</form>
function refreshMap() {
var name = $('#name').val();
}
<script>
$(function() {
$('#name').val(name);
});
</script>
PHP:
$query = "SELECT * FROM register WHERE name IN ('John' || 'Gina')";
$result = mysql_query($query);
if($result === FALSE) {
die(mysql_error());
}
if(!empty($_POST['name']))
{
while($row = mysql_fetch_array($result)){
echo $row['name'];
}
}
EDIT:
$name = htmlspecialchars($_POST['name']);
if(!empty($name))
{
$query = "SELECT * FROM register WHERE name LIKE '" .$name ."'";
$result = mysql_query($query);
if($result === FALSE) {
die(mysql_error());
exit(0);
}
while($row = mysql_fetch_array($result)){
echo $row['name'];
}
}

Categories

Resources