How to create search box in php? - javascript

I have implemented search box for my website by using php, html and jquery.
Firstly, I have created a database,
using php I have sorted the values and
using jquery and html I have shown the search result in a div below the search box.
My problem is that I am not able to select the result using down or up key, for this I also tried to make the result in list or drop box in php.
Please correct me if I am wrong some where. Below is the code which is I am using.
<body>
<h1>Search web page</h1>
<form action="search_demo.php" method="post" >
<input type="text" name="search" placeholder="search here" onkeydown="searchq();" />
<input type="submit" value=">>" />
<div id="output" style="z-index: 10; position: absolute ; background-color: yellow;">
</div>
<div id="stable" style="">
</div>
</form>
</body>
<script>
function searchq(){
var searchtxt = $("input[name='search']").val();
$.post("search_demo12.php", {searchval : searchtxt}, function(output) {
$("#output").html(output);
});
}
</script>
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST['searchval'])){
$search = $_POST['searchval'];
// $search = preg_replace("#[^0-9a-z]#i","",$search);
$pieces = explode(" ", $search);
$pieces_count = count($pieces);
// $pieces[0] = preg_replace("#[^0-9a-z]#i"," ",$pieces[0]);
// $pieces[1] = preg_replace("#[^0-9a-z]#i"," ",$pieces[1]);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "select * from search_demo where fname like '%$search%' or lname like '%$search%'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$pname = $row['fname'];
$purl = $row['lname'];
//if($piece == $row['brand']){
$output .= '<option>'.$pname.' '.$purl.'</option>';
}
}
echo ($output);

Do you mean you cannot select results using up and down keys?
I think it is because you are not wrapping options in select list . Do this
while($row = $result->fetch_assoc()){
$pname = $row['fname'];
$purl = $row['lname'];
//if($piece == $row['brand']){
$output .= '<option>'.$pname.' '.$purl.'</option>';
}
echo "<select>".$output."</select>";

In this case I think that it's better to use onkeyup() JavaScript function as you are implementing live search and need output to be changed dynamically..

Related

How to link my simple jQuery Input with PHP script and Store data into a MYSQL DB?

What I'm trying to do is very simple.
Have a simple input, that allows me to input a name+link, add it to a list and save it to a DB so it's saved.
In my HTML file I currently have:
<form id="form">
<input id="create-input" type="text" placeholder="To do">
<input id="create-link" type="text" placeholder="http://">
<button id="submit" type="button">Add Item</button>
</form>
In my JS file I have:
$(function(){
$('#submit').on('click', addListItem);
});
function addListItem() {
// Grab Input Data
var text = $('#create-input').val();
var link = $('#create-link').val();
// Creating To Do List
$('#todo').append('<li>' +text+' - '+link+ ' <button class="delete">Edit</button> <button class="delete">Delete</button> <button class="delete">Bukkaked!</button></li>');
$('#create-input').val('');
$('#create-link').val('http://');
}
In my PHP file (connecting to DB) I have:
<?php
$servername = "localhost";
$database = "bucketlist";
$username = "bucketuser";
$password = "125632";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "INSERT INTO bucketlist (item, link) VALUES ('Thom', 'www.google.com')";
// Check for Success
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
}
// Check for Fail
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Now I know I need to somehow pass the vars (text and link) through to the PHP file:
$sql = "INSERT INTO bucketlist (item, link) VALUES ('Thom', 'www.google.com')";
But I have no idea how.
Any tips?
Why do you need JQuery you can pass values using php only
here is a change in your code:-
<form id="form" method="post" action="process.php">
<input id="create-input" name="item" type="text" placeholder="To do">
<input id="create-link" name="link" type="text" placeholder="http://">
<button id="submit" type="button">Add Item</button>
</form>
<ul>
<?php include('conn.php');
$sql = "SELECT * FROM bucketlist";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<li>Item-'. $row["item"].' & Link-'. $row["link"].'</li>';
}
} else {
echo "<li>No List</li>";
}
?>
</ul>
conn.php
<?php
$servername = "localhost";
$database = "bucketlist";
$username = "bucketuser";
$password = "125632";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
process.php
<?php
include('conn.php');
$item = $_POST['item'];
$item = $_POST['link'];
$sql = "INSERT INTO bucketlist (item, link) VALUES ($item,$link)";
// Check for Success
if (mysqli_query($conn, $sql)) {
header('location:yourpage.php');
}
// Check for Fail
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Hope this helps.
Use ajax to post the values of the item and link in your html form to your PHP script.
Something like :
var myItem = $('#create-input').html();
var myLink = $('#create-link').html();
$.ajax({
type: 'POST',
url: 'https://yoururl/api/post.php',
data: {item:myItem,link:myLink},
success: SuccessCall,
error : FailureCall,
cache:false,
async:true,
dataType: 'html'
});
function SuccessCall(data,status){
alert("response from server is "+data);
}
function FailureCall(data,status){
alert("Server connection error");
}
Use the PHP script posted by SYB to retrieve the values of item and link that were sent from your html form.

autocomplete using php and html

I want to do text autocomplete using php and html..
i have tried the below code
<?php
$connection = mysqli_connect("localhost", "root", "pass", "data") or die("Error " . mysqli_error($connection));
$sql = "select value from fin";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dna = array();
while ($row = mysqli_fetch_array($result))
{
$dna[] = $row['value'];
}
$jj = array_unique($dna);
print_r(array_values($jj));
?>
result is
my html
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/
themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4
/jquery-ui.js">
</script>
</head>
<body>
<form name="vinform" method="get"> <input type="text" name="editor" autocomplete="on"> <input type="submit" value="Show" id="display"> </form>
<div id="div1"></div>
<script type="text/javascript">
$(function() {
$('#div1').autocomplete({
source: "auto.php"
});
});
</script>
</body>
it doesn't show the words from mysql when i type some word in the text field ..i have to show the related words from mysql based on the text field input,when i type a character in the text field..can anyone help me to solve the issue in my code?
tried with Ajax
var se = null;
$(function () {
var minlength = 1;
$("#editor").keyup(function () {
var that = this,
value = $(this).val();
if (value.length >= minlength ) {
if (se != null)
se.abort();
se = $.ajax({
type: "GET",
url: "auto.php",
data: value,
dataType: "text",
success: function(msg){
if (value==$(that).val()) {
}
}
});
}
});
});
php
<?php
if(isset($_GET['editor']))
{
$con=mysqli_connect("localhost","root","admin321","data");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name=$_GET['editor'];
$sql = "select value from fin where value LIKE '%".$name."'";
$result = mysqli_query($connection, $sql) or
die("Error " . mysqli_error($connection));
$dna = array();
while($row = mysqli_fetch_array($result))
{
$dna[] = $row['value'];
}
$jj=array_unique($dna);
print_r ( $jj);
}
?>
no autocomplete action
With option 1 (Jquery UI autocomplete) and try something like that
<?php
$connection = mysqli_connect("localhost", "root", "pass", "data") or die("Error " . mysqli_error($connection));
$sql = "select value from fin";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dna = array();
while ($row = mysqli_fetch_array($result))
{
$dna[] = $row['value'];
}
echo json_encode($dna);
?>
Jquery UI autocomplete state about source option
String: When a string is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The Autocomplete plugin does not filter the results, instead a query string is added with a term field, which the server-side script should use for filtering the results. For example, if the source option is set to "http://example.com" and the user types foo, a GET request would be made to http://example.com?term=foo. The data itself can be in the same format as the local data described above.
You can use AJAX and Jquery..in html code call the function on keyup event and send data using ajax request after that get data from database using LIKE query and display it..
in input add id="editor"
<input type="text" id="editor" name="editor" autocomplete="on">

How can I add a reply function to comments?

I've created a comment function to my website. I would like to add a reply function to it, but I'm not sure how to do it.
I am able to post comments and retrieve them on the website.
I would like to do a reply function which uses it's "parents" id to show up underneath it.
Desired output:
First Comment
First reply
Second reply
Second Comment
First reply
Second reply
My program looks like this:
<html>
<form action="" method ="POST">
Namn: <br>
<input type="text" name ="name"><br>
Kommentar: <br>
<textarea name="comment" rows="10" cols="20"> </textarea><br>
<input type ="submit" name ="submit" value="Skicka">
</form>
</html>
connectDB
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'com';
$connect = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname) or die(mysqli_error($connect));
?>
getComments
<?php
include ('connectDB.php');
if($connect){
mysqli_select_db($connect, "comments");
$query2 = "SELECT * FROM data ORDER BY `id` DESC";
$result = mysqli_query($connect, $query2);
$comments = array();
while($row = mysqli_fetch_array($result)){
$name = $row['Name'];
$comment = $row['Comment'];
$date = $row['Date'];
echo "
<div style='width:60%' class='col-lg-12'>
<div class='panel panel-default'>
<div class='panel-heading'>
<strong> $name </strong><span style='float:right'class='text-muted'>$date</span>
</div>
<div class='panel-body'>$comment
</div>
</div><!-- /panel panel-default -->
</div><!-- /col-sm-5 -->";
}
}
?>
StoreComments
<?php
if(isset($_POST['submit'])){
$name = htmlentities($_POST['name']);
$comment = htmlentities($_POST['comment']);
$date = date("Y-m-d");
$connect = mysqli_connect("localhost", "root", "");
if($connect){
mysqli_select_db($connect, "comments");
$query = "INSERT INTO data(Name, Comment, Date) VALUES (\"" . $name . "\", \"" . $comment . "\", \"" . $date . "\")";
if(mysqli_query($connect, $query)){
} else {
die ("Failed: " . mysqli_error($connect));
}
} else {
die("Failed to connect to mysql: " . mysqli_errno($connect));
}
}
}
?>
To prevent the N+1 queries problem, when for each comment you make another one query to find replies, you can use the Nested Set Model strategy, like described in this topic: php / Mysql best tree structure
See the post about Managing Hierarchical Data in MySQL.
[UPDATE]
Or if you dont care about performance you can follow this topic solution: Nested comments in PHP & MySQL

Dynamically search SQL table and display on HTML using PHP and JavaScript

I have a form where I want the user to select an Organization from a SQL table and when the form is submitted, the ID of the selected organization should be saved to a different table. I researched online and on SO, and this is what I have now. And it does not work. What's wrong?
Newbrand.php:
<form action="newbrand.php" method="post">
Brand Name: <input type="text" name="bname" /><br><br>
Ogranization: <input type="text" name="searchbar" id="searchbar"><br><br>
<script>
$("#searchbar").keyup(function(){
var searchTerm = $(this).val();
$.post('search.php', { search_term: searchTerm}, function(data){
$(".searchResults").html(data);
$("#searchUl").css("display", "block");
});
});
</script>
Organization ID: <input type="hidden" name="gid" value="" /><br><br>
Gallery ID: <input type="text" name="gid" /><br><br>
</form>
Search.php:
<?php
include 'db_connect.php';
$link = mysqli_connect($host, $username, $password, $db);
$search_term = sanitize(htmlentities($_POST['search_term']));
if (!empty($search_term)){
$search = "(SELECT `Organization_Name` FROM `organizations_info` WHERE `Organization_Name` LIKE '%$search_term%' LIMIT 0, 5) ";
$query = mysqli_query($link, $search);
$result = mysqli_num_rows($query);
while ($row = mysqli_fetch_assoc($query)){
#$user_id = $row['user_id'];
#$username = $row['username'];
$orgname = $row['Organization_Name'];
$check = mysqli_num_rows($query);
if ($check != 0){
echo "<a style='text-decoration: none; color: black;' href='newbrand.php?band=$orgname'><li class='searchResults'>" . ucfirst($orgname) . "</li></a>";
} else {
echo "<li class='searchResults'>No Results Found</li>";
}
}
}
?>
The problem is with your query. It's not passing the value of $search_term, but rather passing it as a string. You may want to use prepared statements and bind the parameter first:
$stmt = mysqli_prepare($link, "SELECT `Organization_Name` FROM `organizations_info` WHERE `Organization_Name` LIKE ? LIMIT 0, 5");
mysqli_stmt_bind_param($stmt, "s", "%{$search_term}%");
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $organizaton_name);
while (mysqli_stmt_fetch($stmt)) {
}
Reference: mysqli SELECT With Prepared Statements
I searched the web for this function and found this. I copyed your source and got it working like this:
$search = "(SELECT Organization_Name FROM organizations_info WHERE Organization_Name LIKE '%". $search_term . "%' LIMIT 0, 5) ";
As you can see I changed the '%". $search_term . "%' , because you can't just place strings in sql query that is between "", you have to cut it in pieces, hope you understand now. I don't go on this site often, so it would be cool if you send me an mail if it fixed the problem to sceptdeckheroes#gmail.com, would like to hear from you, good luck.

Filtering PHP with checkboxes

I am working on this script that will filter sql results based on the which checkboxes are checked. My table is set up like so..
id venue imageurl showingads 2kandunder 2kto4k 4kandup
1 venue1 myurl.com yes yes
2 venue2 myurl.com yes yes
3 venue3 myurl.com no yes
4 venue4 myurl.com yes yes
All code is on the same page. Here is the html..
<form id="form" method="post" action="">
<input type="checkbox" name="2kandunder" class="checkbox" <?=(isset($_POST['2kandunder'])?' checked':'')?>/> 2kandunder<br>
<input type="checkbox" name="2kto4k" class="checkbox" <?=(isset($_POST['2kto4k'])?' checked':'')?>/> 2k to 4k<br>
<input type="checkbox" name="4kandup" class="checkbox" <?=(isset($_POST['4kandup'])?' checked':'')?>/> 4k and up<br>
</form>
Javascript code...
<script type="text/javascript">
$(function(){
$('.checkbox').on('change',function(){
$('#form').submit();
});
});
</script>
and php...
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$dbname = "mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST["2kandunder"])) {
$arguments[] = "`2kandunder` = 'yes'";
}
if (isset($_POST["2kto4k"])) {
$arguments[] = "`2kto4k` LIKE 'yes'";
}
if (isset($_POST["4kandup"])) {
$arguments[] = "4kandup LIKE '%yes%'";
}
if(!empty($arguments)) {
$str = implode(' or ',$arguments);
$qry = "SELECT id, venue, imageurl FROM ads where " . $str . "";
$paginate = new pagination($page, $qry, $options);
} else {
//Whatever happens when there's none checked.
$sql = "SELECT id, venue, imageurl FROM ads WHERE `showingads` = 'yes'";
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<table class='tablebox' width='940' border='1' cellspacing='5'>
<tr><td width='75'>".$row["venue"]."</td></tr>
<tr>
<td width='10'><a href='post_click.php?id=".$row["id"]."'> <img src='".$row["imageurl"]."'></a></td>
</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
When I run this page else query displays which is what I want to happen when page first loads. But when I check any of the checkboxes nothing happens. Here is entire code as it is on page.
<!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 language="JavaScript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
</head>
<html>
<body>
<form id="form" method="post" action="">
<input type="checkbox" name="2kandunder" class="checkbox" <?=(isset($_POST['2kandunder'])?' checked':'')?>/> 2k and under<br>
<input type="checkbox" name="2kto4k" class="checkbox" <?=(isset($_POST['2kto4k'])?' checked':'')?>/> 2k to 4k<br>
<input type="checkbox" name="4kandup" class="checkbox" <?=(isset($_POST['4kandup'])?' checked':'')?>/> 4k and up<br>
</form>
<script type="text/javascript">
$(function(){
$('.checkbox').on('change',function(){
$('#form').submit();
});
});
</script>
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$dbname = "mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST["2kandunder"])) {
$arguments[] = "`2kandunder` = 'yes'";
}
if (isset($_POST["2kto4k"])) {
$arguments[] = "`2kto4k` LIKE 'yes'";
}
if (isset($_POST["4kandup"])) {
$arguments[] = "4kandup LIKE '%yes%'";
}
if(!empty($arguments)) {
$str = implode(' or ',$arguments);
$qry = "SELECT id, venue, imageurl FROM ads where " . $str . "";
$paginate = new pagination($page, $qry, $options);
} else {
//Whatever happens when there's none checked.
$sql = "SELECT id, venue, imageurl FROM ads WHERE `showingads` = 'yes'";
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<table class='tablebox' width='940' border='1' cellspacing='5'>
<tr><td width='75'>".$row["venue"]."</td></tr>
<tr>
<td width='10'><a href='post_click.php?id=".$row["id"]."'> <img src='".$row["imageurl"]."'></a></td>
</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>
My first thoughts is 1. The javascript isn't executing at all? 2. My $arguments is formatted wrong for how I have the database set up? (I have 3 different variations for the arguments to try and test out different formats to see if I could get one to work)
Note: The php portion from tutorial I learned from had the argument like if (isset($_POST["2kandunder"]). I have it like this: if (isset($_POST["2kandunder"])) with the extra parenthesis at the end because I was getting a syntax error for each if statement. If that could be the problem why was I getting syntax errors for each if statement line?
All this code and blabbering but I feel like I am close. Can someone PLEASE help me figure out what the problem is?
EDIT
columns are set up like this..
Field Type Null Key Default Extra
id int(5) NO PRI NULL auto_increment
venue varchar(100) NO NULL
imageurl varchar(150) NO NULL
showingads varchar(5) NO NULL
2kandunder varchar(5) NO NULL
2kto4k varchar(5) NO NULL
4kandup varchar(5) NO NULL
UPDATE
So I have the checkboxes working now but now when I load the page and click the top checkbox (2kandunder) it returns 0 results. The else sql still works for when no checkboxes are checked. I changed the first if statement to
if (isset($_POST["2kandunder"])) {
$arguments[] = "`showingads` = 'yes'";
which should make it the same query as the else sql query when the first (2kandunder) box is checked. Still 0 results shows. So I echoed the $qry to display what query was being run when the first checkbox is checked and it is the exact same as the else $sql query but still returns 0 results? How is this possible if that exact same query works for the else query?
Last Update
The problem was the if $results it was only showing results for the sql query thanks for anyone that helped!
http://api.jquery.com/on/
You are right. javascript isn't executed at all. You are using jquery 1.4.1. But "on" is available since 1.7
I hope this will help you.

Categories