I recently found this tutorial http://www.infotuts.com/create-ajax-based-search-system-php-jquery/ and have noticed that all the results are displayed in search.php while search.php is called through ajax and displayed in index.php. Whenever I tried to integrate it into my website, my index.php contains a variable of $id which is shown in this url: (index.php?id=1) My problem is, I can't seem to get it to know what my $id is. I am unable to change the query in search.php to what I like as a result of this.
$query = mysql_query("select * from userdetail where name like '{$term}%'", $connection);
Here is the original query above me, however I want to have it dependent on the id of the page, so... :
$query = mysql_query("select * from userdetail where id = '$id' AND name like '{$term}%'", $connection);
The only problem is, that search.php has no idea what my $id variable is, even when I load it from index.php it does not work. Can anyone help?
The full code can be seen in the tutorial, but I can show you guys here.
Search.php
<?php
$connection = mysql_connect('localhost', 'root', '12345');
$db = mysql_select_db('userdata', $connection);
$term = strip_tags(substr($_POST['searchit'],0, 100));
$term = mysql_escape_string($term); // Attack Prevention
if($term=="")
echo "Enter Something to search";
else{
$query = mysql_query("select * from userdetail where id = '$id' AND name like '{$term}%'", $connection);
$string = '';
if (mysql_num_rows($query)){
while($row = mysql_fetch_assoc($query)){
$string .= "<b>".$row['name']."</b> - ";
$string .= $row['email']."</a>";
$string .= "<br/>\n";
}
}else{
$string = "No matches found!";
}
echo $string;
}
?>
Here is index.php
<html>
<head>
<title>Ajax Based Search- InfoTuts</title>
<?php
$id = ((int)$_GET["id"]);
?>
<style type="text/css" >
#main {
padding: 10px;
margin: 100px;
margin-left: 300px;
color: Green;
border: 1px dotted;
width: 520px;
}
#display_results {
color: red;
background: #CCCCFF;
}
</style>
<script type="text/javascript "src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
$("#search_results").slideUp();
$("#button_find").click(function(event){
event.preventDefault();
search_ajax_way();
});
$("#search_query").keyup(function(event){
event.preventDefault();
search_ajax_way();
});
});
function search_ajax_way(){
$("#search_results").show();
var search_this=$("#search_query").val();
$.post("search.php", {searchit : search_this}, function(data){
$("#display_results").html(data);
})
}
</script>
</head>
<body>
<div id="main">
<h1>Ajax Based Search System- InfoTuts</h1>
<form id="searchform" method="post">
<label>Enter</label>
<input type="text" name="search_query" id="search_query" placeholder="What You Are Looking For?" size="50"/>
<input type="submit" value="Search" id="button_find" />
</form>
<div id="display_results"></div>
</div>
</body>
</html>
Try this
In search.php file add the following code to accept the id from index.php file
<code>
$term = mysql_escape_string($term); // Attack Prevention
$id = $_POST['id'];
if(!empty($id)) {
$query = mysql_query("select * from userdetail where id = '$id' AND name like '{$term}%'", $connection);
} else {
$query = mysql_query("select * from userdetail where name like '{$term}%'", $connection);
}
if($term=="")
echo "Enter Something to search";
</code>
In the index.php file send the $id variable value along with the ajax request.
<code>
function search_ajax_way(){
$("#search_results").show();
var search_this=$("#search_query").val();
var id_val=$("#id").val();
$.post("search.php", {searchit : search_this, id : id_val}, function(data){ $("#display_results").html(data);}
</code>
In the html add a input hidden field for id
<code>
<form id="searchform" method="post">
<label>Enter</label>
<input type="text" name="search_query" id="search_query" placeholder="What You Are Looking For?" size="50"/>
<input type='hidden' value='<?php echo $id; ?>' id='id'/>
<input type="submit" value="Search" id="button_find" />
</form>
</code>
in
Please mention action='search.php' in form then it will redirect to search.php...and there you will get $id...
Related
MY INDEX PAGE
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Some name</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<br />
<h2 align="center">Search by name</h2><br />
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Search</span>
<input type="text" name="search_text" id="search_text" placeholder="Enter model / search here" class="form-control" />
</div>
</div>
<br />
<div id="result"></div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
AND MY fetch.php PAGE
which is used to get data from the database tables and output results.
I also added if the result is > 50 it will ask to enter few more characters because if I don't add if result > 50 then my page took 20sec to display all data because my database table has 25000 entries.
<?php
$connect = mysqli_connect("localhost", "root", "PASSWORD", "DATABASE");
if(isset($_POST["query"]))
{
$search = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM files
WHERE Name LIKE '%".$search."%'
";
}
else
{
$query = "
SELECT * FROM files ORDER BY ID
";
}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) < 500)
{
$output1 .= '
<div class="table-responsive">
<table class="table table bordered">
<div>
<th>Name</th>
<th>URL</th>
<th>Extension</th>
<th>Download</th>
</div>
';
while($row = mysqli_fetch_array($result))
{
$output2 .= '
<tr>
<td>'.$row["Name"].'</td>
<td>'.$row["URL"].'</td>
<td>'.$row["Extension"].'</td>
</tr>
';
}
if(mysqli_num_rows($result) > 0)
{
echo "$output1";
echo "$output2";
}
else
{
echo 'no results found';
}
}
else
{
echo 'Please enter few more charecters';
}
?>
I want href link for each of my results and on the click, it should download a file from ./"URL" column from a database table.
My database looks like this:
AND MY CURRENT PAGE IS http://mss1996.ddns.net:8008/files
I tried adding < a href=".$row["URL"]."> in outpur'array' but it destroys my page.
You should be able to easily add the URL field to form a valid URL if the contents of that field is indeed a valid URL. What I see missing form your code is http or https if it's an external link. If it's a relative link within the page then you're ok. Then add the </a> to close the link. So you'd form your table column like this:
echo '<td>' . $row["URL"] . '</td>';
I created a web-page,where you can search plant's scientific name. Type plant name in search_text it will give you results in search_result(live search like google and facebook search bar) . Ex: when you will type C in search input, in search result you will get C related search. Like C typed in search input, in search result it will start showing Cucumber(Cucumis sativus), Capsicum(Capsicum annuum), etc.
Now I want when you will click on Cucumber(Cucumis sativus) in search result, it have to direct to home.php/Cucumber . Or when user click on Capsicum(Capsicum annuum), it have to direct on home.php/Capsicum .
And on home.php in body tag I want to display plant name with their scientific name. And in para tag information related to plant search result.
index.php
<!DOCTYPE html>
<html>
<head>
<title>Search</title>
<style type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </style>
<style type="text/javascript">
function searchq() {
var searchTxt = $("input[name='search']").val();
$.get("search.php", {searchVal: searchTxt}, function(output) {
$("#output").html(output);
});
}
</script>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="search" id="myInput1" autocomplete="off"
placeholder="Search username..." onkeydown="searchq(); " />
<input type="submit" value=">>"/>
</form>
<br>
<div id="output"></div>
</body>
</html>
search.php
<?php
$con = mysqli_connect('localhost', 'root');
mysqli_select_db($con, 'plant');
$output = '';
if (isset($_GET['searchVal'])) {
$searchq = $_GET['searchVal'];
$sql = "select * from type where plant like '%$searchq%'";
$query = mysqli_query($con, $sql) or die("could not search");
$count = mysqli_num_rows($query);
if ($count == 0) {
$output = 'There is no serach result';
} else {
while ($row = mysqli_fetch_array($query)) {
$plantname = $row['plant'];
$sciencename = $row['species'];
$id = $row['id'];
$output .= '<div>' . $plantname . ' ' . $sciencename . '</div>';
}
}
}
echo '<a herf="home.php/">' . $output . '</a></div>';
?>
There are many ways of doing this
Passing the name of the plant as a GET param is not an option?
You could do
echo "<a href='home.php?plantname={$plantname}' target='_blank'>{$output}</a></div>";
As the response of your server, that would create the link and in home.php you retrieve the plant name with $_GET['plantname'].
in home.php you do
if(isset($_GET['plantname'])){
echo $_GET['plantname'];
}
Please correct this line in index.php
<style type="text/javascript">
with
<script type="text/javascript">
i'm trying to create an autocomplete box for a form.
Basically what I want to achieve is a textarea field that allows me to search the database for names belonging to a table and add them to a table through a form.
I managed to create this, but it allows me to search only one name at a time, while I would need to look for more names to add to the same textarea.
Basically I have a textarea and this must give me the possibility to insert more names:
name1
name2
...
Where each name is chosen from the drop-down menu that is created. In this way I could go to insert more "names" in the database.
auto_complete.php
<!DOCTYPE html>
<html>
<head>
<title>Autocomplete TextBox</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>
<style>
ul{
background-color:#eee;
cursor:pointer;
}
li{
padding:12px;
}
</style>
</head>
<body>
<br /><br />
<div class="container" style="width:500px;">
<form method="post" action="insert_db.php">
<h3 align="center">Box Text</h3><br />
<label>Enter Name</label>
<br> <textarea name="nominativo" rows="5" cols="30" placeholder="Name Surname" id="nominativo" class="form-control"" ></textarea><br>
<input type="submit" value="Invia">
<div id="nominativoList"></div>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#nominativo').keyup(function(){
var query = $(this).val();
if(query != '')
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#nominativoList').fadeIn();
$('#nominativoList').html(data);
}
});
}
});
$(document).on('click', 'li', function(){
$('#nominativo').val($(this).text());
$('#nominativoList').fadeOut();
});
});
</script>
search.php
<?php
$conn = mysqli_connect("localhost", "root", "123456789", "Personale");
if(isset($_POST["query"]))
{
$output = '';
$query = "SELECT * FROM Squadra WHERE Nominativo LIKE '%".$_POST["query"]."%'";
$result = mysqli_query($conn, $query);
$output = '<ul class="list-unstyled">';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '<li>'.$row["Nominativo"].'</li>';
}
}
else
{
$output .= '<li>Country Not Found</li>';
}
$output .= '</ul>';
echo $output;
}
?>
insert_db.php
<?php
$conn = mysqli_connect("localhost", "root", "123456789", "Personale");
$nominativo = $_POST['nominativo'];
$sql = "INSERT INTO Prenotazione (Nominativo) VALUES ('$nominativo')";
$result = mysqli_query($conn,$sql);
?>
In your opinion how can i do??
Thank you for your attention and for your time.
I am trying to create and edit button, like Reddit has, for my forum. I have got it to work but I was wondering if I'd be able to do it without having to refresh the page.
For example, when I click the edit button, it reloads the page and displays the form for editing, then when I click save it will reload yet again to display the new edited post.
Code (EDITED from IncredibleHat's answer):
<?php
session_start();
$host = "host"; // Host name
$user = "username"; // Mysql username
$password = "password"; // Mysql password
$db_name = "database"; // Database name
$tbl_name = "fquestions"; // Table name
// Connect to server and select databse.
$conn = mysqli_connect($host, $user, $password)or die("cannot connect");
mysqli_select_db($conn, $db_name)or die("cannot select DB");
// get value of id that sent from address bar
$id = $_GET['id'];
$sql = "SELECT * FROM $tbl_name WHERE id='$id'";
$result = mysqli_query($conn, $sql);
$rows = mysqli_fetch_array($result);
/*Check if topic is locked or not */
$locked = $rows['locked'];
if ($_SESSION['username'] == $rows['username']) {
$editPost = true;
}
?>
<head>
<!-- ****** faviconit.com favicons ****** -->
<link rel="shortcut icon" href="../images/favicon.ico">
<!-- ****** faviconit.com favicons ****** -->
<link id ="pageStyle" rel="stylesheet" href='../css/defaultStyle.css' type='text/css'> <!-- Loads Default Stylesheet -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Roboto' type='text/css'>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<div id="mainContent">
<div id="question">
<p id="date"><?php echo $rows['datetime']; ?></p>
<h2><?php echo $rows['topic']; ?></h2>
<b><p><?php echo $rows['username']; ?></p></b>
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = htmlspecialchars($rows['detail']);
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
$url = preg_replace("/^http:/i", "https:", $url);
// make the urls hyper links
echo preg_replace($reg_exUrl, '<a title="Opening this link will take you to a new page" alt="External Link Deleted" target="_blank" href="'.$url[0].'" rel="nofollow">'.$url[0].'</a><br>', '<p id="post">'.$text.'</p>');
} else {
?>
<p id="post"><?php echo htmlspecialchars($rows['detail']); ?></p>
<?php
}
if ($editPost == true) {
$_SESSION['detail'] = $rows['detail'];
$_SESSION['id'] = $rows['id'];
?>
<style>
#editPostButton {
border: none; outline: 0; background-color: #D8D8D8; margin-left: -5px;
}
#editPostButton.dark {
color: white;
background-color: #1C1C1C;
}
</style>
<input type="submit" value="Edit" name="editPostButton" id="editPostButton" data-postId="<?php echo $rows['id']; ?>">
<div id="editFormBlock"></div>
<script>
$(document).ready(function() {
// for clicking on the edit button, to grab the edit form
$("#editPostButton").on('click',function(e) {
e.preventDefault();
$.post(
'ajaxhandler.php',
{ action: 'editform', postid: $(this).data('postId') },
function(htmlReturn) {
$("#editFormBlock").html( htmlReturn ); // replace editForm content
},
'HTML'
);
});
// for clicking the save button for a edit form
// using .on so it catches dynamically added content
$("#editFormBlock").on('click',"#saveButton",function(e) {
e.preventDefault();
var data = $("#editForm").serializeArray();
data.push({name: 'action', value: 'saveform'});
$.post(
'ajaxhandler.php',
data,
function(htmlReturn) {
$("#editFormBlock").html( '' ); // clear edit form out
},
'HTML'
);
});
});
</script>
<?php
}
?>
</div>
<?php
$tbl_name2="fanswer"; // Switch to table "forum_answer"
$sql2 = "SELECT * FROM $tbl_name2 WHERE question_id='$id'";
$result2 = mysqli_query($conn, $sql2);
$row_cnt = mysqli_num_rows($result2);
if ($row_cnt > 0) {
?>
<h3>Replies:</h3>
<div id="replies">
<?php
while($rows = mysqli_fetch_array($result2)) {
?>
<p id="dates"><?php echo $rows['a_datetime']; ?></p>
<div id="reply">
<b><p><?php echo $rows['a_username']; ?></p></b>
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = htmlspecialchars($rows['a_answer']);
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
$url = preg_replace("/^http:/i", "https:", $url);
// make the urls hyper links
echo preg_replace($reg_exUrl, '<a title="Opening this link will take you to a new page" alt="External Link Deleted" target="_blank" href="'.$url[0].'" rel="nofollow">'.$url[0].'</a>', $text);
} else {
?>
<p><?php echo htmlspecialchars($rows['a_answer']); ?></p>
<?php
}
?>
</div>
<?php
}
} else {
?>
<div id="answers">
<p style="color: red;">There doesn't seem to be anything here</p>
<?php
}
$sql3 = "SELECT view FROM $tbl_name WHERE id='$id'";
$result3 = mysqli_query($conn, $sql3);
$rows = mysqli_fetch_array($result3);
$view = $rows['view'];
// if have no counter value set counter = 1
if(empty($view)) {
$view = 1;
$sql4 = "INSERT INTO $tbl_name(view) VALUES('$view') WHERE id='$id'";
$result4 = mysqli_query($conn, $sql4);
}
// count more value
$addview = $view+1;
$sql5 = "update $tbl_name set view='$addview' WHERE id='$id'";
$result5 = mysqli_query($conn, $sql5);
mysqli_close($conn);
?>
</div>
<h3>Post A Reply:</h3>
<form name="form1" method="post" action="add-answer" autocomplete="off">
<label>Reply: </label>
<?php
if ($locked == 1) {
echo '<textarea name="a_answer" id="a_answer" style="width: 800px;" readonly>🔒 This topic is locked! 🔒</textarea><br>';
} else if ($_SESSION['logged_in'] != true) {
echo '<textarea name="a_answer" id="a_answer" style="width: 800px;" readonly>⛔ You must login to reply! ⛔</textarea><br>';
} else {
echo '<textarea name="a_answer" id="a_answer" maxlength="300" required style="width: 800px;"></textarea><br>
<div class="g-recaptcha" data-sitekey="6LdrxD4UAAAAACAaVAR6U9BjOEDC9-j4QaOzBsFh"></div>
<input type="submit" name="submit" value="Submit">
<input type="reset" name="reset" value="Reset">';
}
?>
<input name="id" type="hidden" value="<?php echo $id; ?>">
</form>
</div>
</body>
ajaxhandler.php:
<?php
session_start();
$detail = $_SESSION['detail'];
$id = $_SESSION['id'];
if (!empty($_POST['action'])) {
if ($_POST['action'] == 'editform') {
?>
<style>
#post, #editPostButton {
display: none;
}
#saveButton {
border: none; outline: 0; background-color: #D8D8D8; margin-left: -5px;
}
</style>
<form id="editForm">
<textarea name="detail"><?php echo $detail; ?></textarea><br>
<input type="button" id="saveButton" value="Save">
</form>
<?php
}
if ($_POST['action'] == 'saveform') {
// do save process to db
// echo out a new static post html block
$host = "host"; // Host name
$user = "username"; // Mysql username
$password = "password"; // Mysql password
$db_name = "database"; // Database name
$tbl_name = "fquestions"; // Table name
// Connect to server and select databse.
$conn = mysqli_connect($host, $user, $password)or die("cannot connect");
mysqli_select_db($conn, $db_name)or die("cannot select DB");
$sql = "UPDATE $tbl_name SET detail = '$detail' WHERE id=$id";
$result = mysqli_query($conn, $sql);
}
}
?>
Two ways you could do the toggling of an edit form.
Load in more html (sub parts, not whole html documents) with ajax calls, and replace existing elements with the new html chunks based on actions. Click the edit button, it calls ajax to 'get the form block', and then it replaces some slot on the page with it. Submitting the form, tosses that form, and replaces it with the new static text block. This is generally a cleaner way to handle it.
Have all the relevant bits in the html DOM on first load of the php script. Have many parts hidden. Then clicking certain buttons, or doing actions shows/hides elements based on those actions. This is easier, but not as clean, as all your form submit elements and actions, as well as the original static parts, are all in the HTML on every general page load.
An example of loading in a edit form on edit-button click, and swapping content blocks:
Basic static HTML framework (from first load of main.php):
<p id="post">[the original post html here]</p>
<?php if ($editPost == true) { /* dont bother if they have no edit rights */?>
<input type="button" id="editPostButton" value="Edit" data-postId="<?php echo $postId;?>">
<div id="editFormBlock"></div>
<?php }?>
Script area (jquery required):
<script language="Javascript" type="text/javascript">
$(document).ready(function() {
// for clicking on the edit button, to grab the edit form
$("#editPostButton").on('click',function(e){
e.preventDefault();
$.post(
'ajaxhandler.php',
{ action: 'editform', postid: $(this).data('postId') },
function(htmlReturn){
$("#editFormBlock").html( htmlReturn ); // replace editForm content
},
'HTML'
);
});
// for clicking the save button for a edit form
// using .on so it catches dynamically added content
$("#editFormBlock").on('click',"#saveButton",function(e){
e.preventDefault();
var data = $("#editForm").serializeArray();
data.push({name: 'action', value: 'saveform'});
$.post(
'ajaxhandler.php',
data,
function(htmlReturn){
$("#post").html( htmlReturn ); // replace static post content
$("#editFormBlock").html( '' ); // clear edit form out
},
'HTML'
);
});
});
</script>
The ajaxhandler.php:
// Have blocks that pertain to the $_POST['action']
if (!empty($_POST['action'])) {
if ($_POST['action'] == 'editform') {
// do a database select on using the postId
// grab the data you wish to use in the edit form
// build a form and echo it out for the ajax return
echo '
<form id="editForm">
<input type="hidden" name="postId" value="'. $row['id'] .'">
<textarea name="detail">'. $row['detail'] .'</textarea>
<input type="button" id="saveButton" value="Save">
</form>
';
}
if ($_POST['action'] == 'saveform') {
// put your "save to database" code here
// that uses $_POST['postId'], $_POST['detail'] etc
// after saving, grab a fresh copy of the post
// and then echo out a new static html #post content
echo htmlspecialchars($row['detail']);
}
}
I hope this was clear enough to understand to get a foothold on what you wish to do. There is a lot more you can do, with an extra errorBlock to show errors, and handling of results. You can even push in some animations too. Endless possibilities.
NOTE: I should warn you though, that this is all based off your example, where you are showing just one post, and one edit form. This uses "ID"s, which must be unique on the page. If you are planning on pouring many posts on ONE page, you will need to adjust everything to use classes and enumerated ID's to keep the unique.
I am new to coding and have no clue. I managed to grap this script from this site http://www.99points.info/2010/12/n-level-dynamic-loading-of-dropdowns-using-ajax-and-php/
I amended the titles and field inputs to match my project requirements instead of the ones used in the demo. I managed to get this working on my project with reference to the drop down lists.
The problem i am having now is how do you make the script accept the values and input it into the database after the customer selects the drop down lists and clicks the submit button.
If there is a better way to rewrite these codes?
Please i am in need of help. Thank you!
here is the code i got on the "get_child_categories.php" file:
<?php
include('cn.php');
if($_REQUEST)
{
$id = $_REQUEST['parent_id'];
$query = "select * from tour where pid = ".$id;
$results = #mysql_query( $query);
$num_rows = #mysql_num_rows($results);
if($num_rows > 0)
{?>
<select name="sub_category" class="parent">
<option value="" selected="selected">-- Sub Category --</option>
<?php
while ($rows = mysql_fetch_assoc(#$results))
{?>
<option value="<?php echo $rows['tour_id'];?>"><?php echo $rows
['category'];?></option>
<?php
}?>
</select>
<?php
}
else{echo '<label style="padding:7px;float:left; font-size:12px;">No Record Found
!</label>';}
}
?>
Also note that the "No Record Found" is always displayed after selecting all drop down lists at the end. How do i fix this to show every criteria is met before submission?
This is the "booking.php" form:
<!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" xml:lang="en" lang="en">
<head>
<link href="style.css" rel="stylesheet" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Jurassic Tours/booking form</title>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript" src="jquery.livequery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//$('#loader').hide();
$('.parent').livequery('change', function() {
$(this).nextAll('.parent').remove();
$(this).nextAll('label').remove();
$('#show_sub_categories').append('<img src="loader.gif" style="float:left;
margin-top:7px;" id="loader" alt="" />');
$.post("get_chid_categories.php", {
parent_id: $(this).val(),
}, function(response){
setTimeout("finishAjax('show_sub_categories', '"+escape(response
)+"')", 400);
});
return false;
});
});
function finishAjax(id, response){
$('#loader').remove();
$('#'+id).append(unescape(response));
}
</script>
<style>
.both h4{ font-family:Arial, Helvetica, sans-serif; margin:0px; font-size:14px;}
#search_category_id{ padding:3px; width:200px;}
.parent{ padding:3px; width:150px; float:left; margin-right:12px;}
.both{ float:left; margin:0 0px 0 0; padding:0px;}
</style>
</head>
<?php
include('cn.php');?>
<body>
<div id="main">
<div id="header">
<img src="images/banner.jpg" alt="Banner" style="padding:10px"/>
</div>
<div id="mylinks">
<div id="navcontainer">
<ul>
<li>Home</li>
<li>Login</li>
<li>Register</li>
<li>Booking</li>
<li>About Us</li>
<li>Services</li>
<li>Feedback</li>
<li>Agency Login</li>
<li>Logout</li>
</div>
</div>
<div id="content">
<h2><center>PLEASE PLACE YOUR BOOKING</center></h2>
<div style="padding-left:30px; height:710px;">
<br clear="all" /><br clear="all" />
<form action="booking.php" method="post">
<div id="show_sub_categories">
<select name="search_category" class="parent">
<option value="" selected="selected">-- Categories --</option>
<?php
$query = "select * from tour where pid = 0";
$results = mysql_query($query);
while ($rows = mysql_fetch_assoc(#$results))
{?>
<option value="<?php echo $rows['tour_id'];?>"><?php echo $rows
['category'];?></option>
<?php
}?>
</select>
</div>
<br clear="all" /><br clear="all" />
<input type="submit" name="submit" value="submit">
</form>
<br clear="all" /><br clear="all" />
</div>
</body>
</html>
The booking form is getting data from the tour table in the database where there is tour,destination,and duration all dependant on drop down lists selected.
This is the processing part where i do not know how to do after the submit button is pressed so i left it blank! The only data i can recover is the Primary key from the customer table as shown below.
<?php
//When submit button is pressed.
if (isset($_POST['submit'])) {
//Include the server and database connection.
include('cn.php');
session_start();
$userUsername = $_SESSION['loggedInUser'];
// Build the SQL query to retreive the variables ($) and input the data into the database.
$sql = "INSERT INTO booking
(user_id)
VALUES ((SELECT user_id FROM user WHERE user_username =
'" . $userUsername . "'))";
// test the sql statement.
if(!mysql_query($sql,$cn)) {
die(mysql_error($cn));
}
// direct to this page when booking is successful.
header('Location: booking_success.php');
}
?>
I forgot to include the update.php file
<?php
if (!empty($_GET['tour_id']) && !empty($_GET['value'])) {
$id = $_GET['tour_id'];
$value = $_GET['value'];
try {
$objDb = new PDO('mysql:host=localhost;dbname=jurassicbase', 'root', '');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM `categories`
WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($value));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if (!empty($list)) {
$out = array('<option value="">Select one</option>');
foreach($list as $row) {
$out[] = '<option value="'.$row['tour_id'].'">'.$row
['name'].'</option>';
}
echo json_encode(array('error' => false, 'list' => implode('', $out)));
} else {
echo json_encode(array('error' => true));
}
} catch(PDOException $e) {
echo json_encode(array('error' => true));
}
} else {
echo json_encode(array('error' => true));
}
I'm guessing you are never reaching the form processor as you don't have any <form> tag in your form page.
You would need:
<form action="your_form_processor.php" method="post">
// your form fields
</form>
to get that to work.
Apart from that you need to switch to PDO (or mysqli) and prepared statements as your code is vulnerable to sql injection.
While you are developing your code, you should also remove all # error suppressing operators.