php form that requests data based on user select - php

I have edited this based on help already received. I seem to be having issues with how the information is being called from the database. I keep getting errors of no results found so to speak. I think I got a pretty good idea what might be the cause, but I am not sure to rectify this.
Originally this search function was set up differently. I had an html page that had a dropdown list each option was assigned a value, this being text i.e.
<option Value="North East">North East</option>
However because I have separate tables in the database that control the population of the drop downs, the value is no longer being text but a number.
Any ideas on how to combat this?
This is currently what I have from head to toe.
<!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=iso-8859-1" />
<title>Results</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".country").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax_city.php",
data: dataString,
cache: false,
success: function(html)
{
$(".city").html(html);
}
});
});
});
</script>
<style>
body {
color: #FFFFFF;
}
#theclub{
border:1px solid white;
padding: 10px;
}
label
{
font-weight:bold;
padding:10px;
}
</style>
<link rel="stylesheet" type="text/css" href="Style.css">
<script type='text/javascript' src='style2.js'></script>
</head>
<body>
<form method="POST" enctype="multipart/form-data">
<label>Country :</label> <select name="country" class="country">
<option selected="selected">--Select Country--</option>
<?php
include('db.php');
$sql=mysql_query("select id,data from data where weight='1'");
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$data=$row['data'];
echo '<option value="'.$id.'">'.$data.'</option>';
} ?>
</select>
<label>City :</label> <select name="city" class="city">
<option selected="selected">--Select City--</option>
</select>
<input type="submit" value="Search" name="submit">
</form>
<?php
if(isset($_POST['submit']) && $_POST['submit'] != ""){ } //--here is the condition that is true if search button is pressed
$selectedOption = $_POST["city"];
$result = mysqli_query($con,
sprintf("SELECT * FROM `SouthYorkshire` WHERE `EstProv` = '%s'",
preg_replace("/[^A-Za-z ]/", '', $selectedOption)));
echo "<div id=\"Results\">";
while($row = mysqli_fetch_array($result))
{
echo "<div id=\"theclub\">";
echo "<div class=\"ClubName\">";
echo $row['EstName'];
echo "</div><br>";
echo "<div class=\"Location\">";
echo $row['EstAddress2'];
echo "</div>";
echo "<br>";
echo "<div id=\"website\"><img src=\"photos/more-info.png\" width=\"75\" height=\"25\"/> <img src=\"photos/visit-website-button.png\" width=\"75\" height=\"25\" /></div></div>";
echo "<br>";
}
echo "</div>";
mysqli_close($con);
?>
<br>
</body>

I'm shooting in the dark a bit because I'm not sure what you mean by first and second code...
If you want only one part of the code to run you need some sort of condition to check if to run it or not
If you don't want the second part of the code run right away you want to check if the post variable city is set and not empty and only run the code if the value isn't empty:
if(isset($_POST['city']) && $_POST['city'] != ""){
// your code here
}

Your second code should be enclosed within a if condition in order to run it after the first code exicution like the following way-
But first you have to add name attribute to your search button in first code-
<input type="submit" value="Search" name="submit">
and now your second code should be--
if($_POST['submit']) //--here is the condition that is true if search button is pressed
{
$selectedOption = $_POST["city"];
$result = mysqli_query($con,
sprintf("SELECT * FROM `SouthYorkshire` WHERE `EstProv` = '%s'",
preg_replace("/[^A-Za-z ]/", '', $selectedOption)));
echo "<div id=\"Results\">";
while($row = mysqli_fetch_array($result))
{
echo "<div id=\"theclub\">";
echo "<div class=\"ClubName\">";
echo $row['EstName'];
echo "</div><br>";
echo "<div class=\"Location\">";
echo $row['EstAddress2'];
echo "</div>";
echo "<br>";
echo "<div id=\"website\"><img src=\"photos/more-info.png\" width=\"75\" height=\"25\"/> <img src=\"photos/visit-website-button.png\" width=\"75\" height=\"25\" /></div></div>";
echo "<br>";
}
echo "</div>";
mysqli_close($con);
?>
}

Related

Form and PHP result display on same page

I have a form on one page linking to a PHP file (action), now the PHP result is being displayed in this PHP file/page. But I want the result to be displayed on the page with the form. I have searched thoroughly and couldn't find it anywhere. Perhaps any of you can help?
Code: /citizens.php (main page)
<form method="post" action="/infoct.php">
<input type="text" name="ID" placeholder="ID">
<input name="set" type="submit">
</form>
Code: /infoct.php
<!DOCTYPE html>
<html>
<head>
<!-- <meta http-equiv="refresh" content="0; url=/citizens.php" /> -->
</head>
<body>
<?php {
$ID2 = isset($_POST['ID']) ? $_POST['ID'] : false;
}
$connect = mysql_connect('localhost', 'root', 'passwd');
mysql_select_db ('inhabitants');
$sql = "SELECT `Name`, `Surname`, `DOB`, `RPS`, `Address` FROM `citizens` WHERE ID = $ID2";
$res = mysql_query($sql);
echo "<P1><b>Citizen Identification number is</b> $ID2 </p1>";
while($row = mysql_fetch_array($res))
{
echo "<br><p1><b>First Name: </b></b>", $row['Name'], "</p1>";
echo "<br><p1><b>Surname: </b></b></b>", $row['Surname'], "</p1>";
echo "<br><p1><b>Date of birth: </b></b></b></b>", $row['DOB'], "</p1>";
echo "<br><p1><b>Address: </b></b></b></b></b>", $row['Address'], "</p1>";
echo "<br><p1><b>Background information: </b><br>", $row['RPS'], "</p1>";
}
mysql_close ($connect);
?>
</body>
</html>
My fixed code thanks to Marc B
<form method="post">
<input type="text" name="ID" placeholder="ID">
<input name="set" type="submit">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$ID = isset($_POST['ID']) ? $_POST['ID'] : false;
$connect = mysql_connect('fdb13.biz.nf:3306', '1858208_inhabit', '12345demien12345');
mysql_select_db ('1858208_inhabit');
$sql = "SELECT `Name`, `Surname`, `DOB`, `RPS`, `Address` FROM `citizens` WHERE ID = $ID";
$res = mysql_query($sql);
if ($ID > 0) {
echo "<p><b>Citizen Identification number is</b> </p>";
while($row = mysql_fetch_array($res))
echo "<br><p><b>Surname: </b></b></b>", $row['Surname'], "</p>";
echo "<br><p><b>First Name: </b></b>", $row['Name'], "</p>";
echo "<br><p><b>Date of birth: </b></b></b></b>", $row['DOB'], "</p>";
echo "<br><p><b>Address: </b></b></b></b></b>", $row['Address'], "</p>";
echo "<br><p><b>Background information: </b><br>", $row['RPS'], "</p>";
mysql_close ($connect);
}
else {
echo "<p>Enter a citizen ID above</p>";
}
}
?>
DB Snap
A single-page form+submit handler is pretty basic:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... form was submitted, process it ...
... display results ...
... whatever else ...
}
?>
<html>
<body>
<form method="post"> ... </form>
</body>
</html>
That's really all there is.
Use code on the same page (citizens.php)
<?php
if (isset($_POST)) {
Do manipulation
}
?>
Else use ajax and remove action method from form.
<form method="post" id="contactForm">
<input type="text" name="ID" placeholder="ID">
<input name="set" type="buttom" id="submitId">
</form>
<script>
$("#submitId").click(function(){
var Serialized = $("#contactForm").serialize();
$.ajax({
type: "POST",
url: "infoct.php",
data: Serialized,
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function(){
alert('error handing here');
}
});
});
</script>
And in your infact.php in the end Echo the data so that ajax will have the data in return.
You could just put everything in infoct.php, like this:
<!DOCTYPE html>
<html>
<head>
<!-- <meta http-equiv="refresh" content="0; url=/infoct.php" /> -->
</head>
<body>
<form method="post" action="/infoct.php">
<input type="text" name="ID" placeholder="ID" value="<?php isset($_POST['ID']) ? $_POST['ID'] : '' ?>">
<input name="set" type="submit">
</form>
<?php
if (isset($_POST['ID'])) {
$ID2 = $_POST['ID']; // DO NOT FORGET ABOUT STRING SANITIZATION
$connect = mysql_connect('localhost', 'root', 'usbw');
mysql_select_db ('inhabitants');
$sql = "SELECT `Name`, `Surname`, `DOB`, `RPS`, `Address` FROM `citizens` WHERE ID = $ID2";
$res = mysql_query($sql);
echo "<P1><b>Citizen Identification number is</b> $ID2 </p1>";
while($row = mysql_fetch_array($res))
{
echo "<br><p1><b>First Name: </b></b>", $row['Name'], "</p1>";
echo "<br><p1><b>Surname: </b></b></b>", $row['Surname'], "</p1>";
echo "<br><p1><b>Date of birth: </b></b></b></b>", $row['DOB'], "</p1>";
echo "<br><p1><b>Address: </b></b></b></b></b>", $row['Address'], "</p1>";
echo "<br><p1><b>Background information: </b><br>", $row['RPS'], "</p1>";
}
mysql_close ($connect);
}
?>
</body>
</html>
Do not forget about string sanitization !
I have found the solutions to the folowing problems:
Display results on same page
Thanks to Marc B
A single-page form+submit handler is pretty basic:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... form was submitted, process it ...
... display results ...
... whatever else ...
}
?>
<html>
<body>
<form method="post"> ... </form>
</body>
</html>
That's really all there is.
Only first value is showing
I resolved this problem by adding this to my code:
while($row = mysql_fetch_array($res)) {
$surname=$row['Surname'];
$name=$row['Name'];
$dob=$row['DOB'];
$address=$row['Address'];
$RPS=$row['RPS'];
Now all the values are being displayed instead of only the first one.
Display results on same page
Well I've stumbled upon this with the same problem
and I found out you can simply require the other file.
include_once("PATH_TO_FILE")'.
in /citizens.php
<?php include_once="infoct.php" ?>
<form> ... </form>
<div>
<?php $yourdata ?>
</div>
$yourdata should be html.
Do not forget about string sanitization !
Make sure to remove action from the form
Better than having all logic and Html in one file.

value selected in dropdown when back to this page php through ajax

There are two dropdown . one loaded with province and other is loaded with district on change the province from dropdown. How to show selected items in both dropdown when error occur or any other reason redirect to test.php page. ?? When i back to this page province dropdown is selected but district not selected..
Test.php
<?php
include "connection.php";
$msg = "";
if(isset($_REQUEST['msg']) && !empty($_REQUEST['msg']))
{
$msg = $_REQUEST['msg'];
}
if ( isset($_SESSION['province']) && !empty($_SESSION['province']) )
{
$province = $_SESSION['province'];
}
# Get Province
$sqlProvince = "SELECT * FROM tbl_province";
$resProvince = mysql_query($sqlProvince) or die(mysql_error());
?>
<!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" />
<title>Untitled Document</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js"></script>
<script type="text/javascript">
function showDistrict(province){
$("#district").html(' '); // city
$.ajax({
url: "js/ajaxDistrict.php",
type: 'POST',
//dataType: 'json',
data: {'province': province},
//dataType: 'json',
cache: false,
success: function(data){
$("#district").html(data);
}
});
}
</script>
</head>
<body>
<?php echo $msg; ?>
<form id="myfrom" action="showTest.php" method="get">
<p>
`enter code here`<label>Province:<small>*</small></label>
<select name="province" id="province" onchange="showDistrict(this.value);" required>
<option value="">-SELECT-</option>
<?php
if(mysql_num_rows($resProvince) > 0)
{
while($rowProvince = mysql_fetch_array($resProvince)){
?>
<option value="<?php echo $rowProvince['Name'];?>"<?php if( $province == $rowProvince['Name'] ) { echo "selected='selected'";} ?>"><?php echo $rowProvince['Name'];?></option>
<?php }
} ?>
</select>
</p>
<p>
<label>Postal City District:<small>*</small></label>
<select name="district" id="district" >
<option value="">-SELECT-</option>
<option value="<?php echo $_SESSION['district']['City_District'];?>"><?php echo $_SESSION['district']['City_District'];?></option>
</select>
</p>
<input name="submit" type="submit" />
</form>
</body>
</html>
ajaxDistrict.php
<?php
include "../connection.php";
$res = "";
$province = $_REQUEST['province'];
$_SESSION['province'] = $province;
$query="SELECT * FROM districts WHERE Province = '".$province."' ";
$result=mysql_query($query) or die(mysql_error());
$str = "";
//$_SESSION['district'] = array();
if(mysql_num_rows($result)>0)
{
while($row = mysql_fetch_array($result))
{
$_SESSION['district']['City_District'] = trim($row['City_District']);
$City_District = trim($row['City_District']);
if($_SESSION['district']['City_District'] == $City_District) { $str = "selected='selected'";}
$res .= "<option value=\"".$City_District."\" ".$str." >".$City_District."</option>";
}
}
else{
$res .= "<option value=''>-SELECT-</option>";
}
echo $res;
?>
You have to keep the value of province and district in session so you can populate it back accordingly or can use cookie for the same.
Call showDistrict function on load of the page in script
`$(document).ready(function(){
showDistrict();
});
`
i think this will work...

Having a hard time with displaying information from my database

I'm just learning PHP and I followed the book to the last detail and when I go to the localhost web page that I created to pull information from the database nothing shows on the webpage. I've troubleshooted all night I've Google and read the book over and over to see what I missed. I'm posting the code that I wrote to see if someone can lead me in the right area to fix my problem.
<html>
<head>
<title>Pay Scale</title>
<style type="text/css">
table {
background-color: #FCF;
}
th {
width:150px;
text-align: left;
}
</style>
</head>
<body>
<h1>Pay Scale</h1>
<form method= "post" action= "Payscale.php"
<input type="hidden" name="submitted" value="true" />
<label> Search Category:
<select name="category">
<option value="Id">ID</option>
<option value="First Name">First Name</option>
<option value="Last_Name">Last_Name</option>
</select>
</label> <label>Search Criteria:
<input type="text" name="criteria" />
</label>
<input type="submit" />
</form>
<?php
if (isset($_POST['submitted'])){
include('payconnect.php');
$category = $_POST['category'];
$criteria = $_POST['criteria'];
$query = "SELECT * FROM employee pay range WHERE $category = '$criteria'";
$result = mysqli_query($dbcon, $query) or die('error getting data');
echo "<table>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last_Name</th> <th>Pay_Range</th> </tr>";
While($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "<tr><td>";
echo $row['ID'];
echo "</td><td>";
echo $row['First Name'];
echo "</td><td>";
echo $row['Last_Name'];
echo "</td><td>";
echo $row['Pay_Range'];
echo "</td><tr>";
}
echo "<table>";
}
?>
</body>
</html>
There are a couple of problems with the html code for the page. The most obvious is that there is no closing > on your form tag, so the browser slurps up the next line, thinking that it is part of the form tag. Since that line sets the $_POST['submitted'] variable that your PHP script is looking for, the value doesn't get set and the script never runs.
To correct the problem, just add a > to your form declaration:
<form method="post" action="Payscale.php">
There are also a few other problems in the HTML that could be fixed at the same time:
At the top of the page:
<html>
<head>
A document should start with a DOCTYPE declaration so that the browser knows how to interpret the page. For HTML5, this is as simple as adding a line to the start of your file:
<!DOCTYPE html>
<html>
<head>
There is also an error in the table creation code:
echo $row['Last_Name'];
echo "</td><td>";
echo $row['Pay_Range'];
echo "</td><tr>"; # A
}
echo "<table>"; # B
The lines marked A, and B create new elements--a table row, and a new table respectively. You should be closing the elements--i.e. using </tr> and </table>.
It appears that your opening tag is not closed (a minor syntactical error).
Try changing it from this:
<form method= "post" action= "Payscale.php"
to this:
<form method="post" action="Payscale.php">
and see if that solves the problem.
Try this it's working :
<html>
<head>
<title>Pay Scale</title>
<style type="text/css">
table {
background-color: #FCF;
}
th {
width:150px;
text-align: left;
}
</style>
</head>
<body>
<h1>Pay Scale</h1>
<form method= "post" action="Payscale.php">
<input type="hidden" name="submit" value="true"/>
<label> Search Category:
<select name="category">
<option value="Id">ID</option>
<option value="First Name">First Name</option>
<option value="Last_Name">Last_Name</option>
</select>
</label> <label>Search Criteria:
<input type="text" name="criteria" />
</label>
<input type="submit" value="submit" name="submitted"/>
</form>
</body>
</html>
Payscale.php
<?php
if (isset($_POST['submitted'])){
include('payconnect.php');
$category = $_POST['category'];
$criteria = $_POST['criteria'];
$query = "SELECT * FROM employee pay range WHERE $category = '$criteria'";
$result = mysqli_query($dbcon, $query) or die('error getting data');
echo "<table>";
echo "<tr> <th>ID</th> <th>First Name</th> <th>Last_Name</th> <th>Pay_Range</th> </tr>";
While($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "<tr><td>";
echo $row['ID'];
echo "</td><td>";
echo $row['First Name'];
echo "</td><td>";
echo $row['Last_Name'];
echo "</td><td>";
echo $row['Pay_Range'];
echo "</td><tr>";
}
echo "<table>";
}
?>

What is wrong with this php search page?

I found a tutorial that looked like it would do what I've been trying to do without success. I adapted it to my details and tried it. It doesn't work. When you enter the search and hit submit, all it does is go back to the beginning. I can't see anything wrong with the code so after a couple of hours of trying things, here it is. Can you see what is wrong?
<!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" />
<title>test</title>
</head>
<body>
<?
if ($searching =="yes")
{
echo "<h2>Search</h2><p>";
if ($find == "")
{
echo "<p>You forgot to enter a search term";
exit;
}
mysql_connect('localhost', 'user', 'password') or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
$data = mysql_query("SELECT * FROM engravers WHERE upper($field) LIKE'%$find%'");
while($result = mysql_fetch_array( $data ))
{
echo $result['Country'];
echo "<br>";
echo $result['Year'];
echo "<br>";
echo $result['Engraver1Surname'];
echo "<br>";
echo $result['Designer1Surname'];
echo "<br>";
echo $result['Printer'];
echo "<br>";
echo "<br>";
}
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
echo "<b>Searched For:</b> " .$find;
}
?>
<h2>Search</h2>
<form name="search" method="post" action="<?=$PHP_SELF?>">
Search for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="Country">Country</option>
<Option VALUE="Year">Year</option>
<Option VALUE="Engraver1Surname">Engraver</option>
<Option VALUE="Designer1Surname ">Designer</option>
<Option VALUE="Printer">Printer</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" value="Search" />
</form>
</body>
</html>
As mentioned in my comment, after POSTing, you need to grab the variables from the $_POST array. Something like:
if ($_POST['searching'] == "yes") {
$find = $_POST['find'];
$field = $_POST['field'];
// etc...
This looks like very old PHP code that had register_globals on. It doesn't work like that anymore.
Use the superglobal $_POST to get to your variables, for example:
if ($_POST['searching'] =="yes") {
...
}
Also, read into SQL injection and how to avoid it.
You need to set the variables on begin:
//set default values
$find="";
$searching="";
$field="";
If(isset($_POST['searching']) && $_POST['searching']="yes"){
$find= mysql_real_escape_string($_POST['find']);
$searching=mysql_real_escape_string($_POST['searching']);
$field=mysql_real_escape_string($_POST['field']);
...

add a jquery date picker to php list

I have a mysql database table which contains a error code, date and mail address.
My script below displays a basic list as per the screenshot,
I would like to be able to filter by date, I am hoping to use jquery date picker.
The idea being, only show entries where the date matches that in the jquery date picker.
The php code used to display the list:
<?php
// Add Logo
$image = "logo.png";
$width = 300;
$height = 280;
echo '<img src="'.$image.'" style=width:"' . $width . 'px;height:' . $height . 'px;">';
// Make a MySQL Connection
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("pmta_reporting") or die(mysql_error());
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM address")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Error</th> <th>Date</th> <th>Mail Address</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['code'];
echo "</td><td>";
echo $row['date'];
echo "</td><td>";
echo $row['address'];
echo "</td></tr>";
}
echo "</table>";
// disconnect from the database
mysql_close();
?>
The code I am using for the date picker is
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/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.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</head>
<body>
<p>Date: <input type="text" id="datepicker" /></p>
</body>
</html>
How can I add the jquery date picker to the script so that when a user selects a date the results shown on the page only display the date selected by the user?
On value change in datepicker field, reload url with GET variable date:
$( "#datepicker" ).change(function(){
window.location.href = window.location.href + '?date=' + $(this).val();
})
in php, if get variable is suplied add a where statement to the query:
$query = "SELECT * FROM address"
if (isset( $_GET['date']) && ($date = $_GET['date'])){
$query .= " WHERE date = '$date'";
}
$result = mysql_query($query)
NOTE! this wont protect against sql injection!
This would be a bit complicated to write up, so forgive me for not writing an example, but I'll give you a good idea of how to do this. First of all, you should make a separate PHP file that returns only the table and takes a POST variable argument for the date that it uses to filter the results in the SQL query. Next, use jQuery's .change() on the input field that is the datepicker to make an $.ajax call with $('#datepicker').val() set in the data argument to the PHP file that returns your data and load it into a specified <div>.
You can read more about $.ajax here: http://api.jquery.com/jQuery.ajax/
Might not be very efficient, but you can do this.
$("#date").datepicker({"dateFormat": "yy-mm-dd"});
$("#date").change(function() {
var date_from_date_picker = $(this).val();
$('td.date').each(function() {
if ($(this).text() != date_from_date_picker) {
$(this).parent().hide();
} else {
$(this).parent().show();
}
});
});
Working demo at http://jsfiddle.net/djhPN/2/
In your HTML:
<body>
<form method="get" action="yourphpscript">
<p>Date: <input type="text" name="date" id="datepicker" /></p>
<input type="submit" value="Search" />
</form>
</body>
In your PHP you can use PDO or mysqli, that way you can use prepared statements and parameterized queries that protect you against SQL-injection.
Check out this post for more information:
Examples of PDO & mysqli
You could also escape the bad sql with the function "mysql_real_escape_string($bad_variable)"
I'll just adjust the code of Joel Harkes to make it work against SQL-injection also:
$query = "SELECT * FROM address"
if (isset( $_GET['date']) && ($date = mysql_real_escape_string($_GET['date']))){
$query .= " WHERE date = '$date'";
}
$result = mysql_query($query)
You want to use ajax to load the content like this.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/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.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
jQuery(document).ready(function() {
$("#datepicker").change(function(){
var new_date = $(this).val();
jQuery.ajax({
type: "POST",
url: "http://www.url.php",
data: { date:new_date },
success: function( data ) {
$('#displaycontent').val(data);
}
});
});
});
</script>
</head>
<body>
<p>Date: <input type="text" id="datepicker" /></p>
<div id="displaycontent"> </div>
</body>
</html>
and ajax file is ex. url.php is like this.
// Add Logo
$image = "logo.png";
$width = 300;
$height = 280;
echo '<img src="'.$image.'" style=width:"' . $width . 'px;height:' . $height . 'px;">';
// Make a MySQL Connection
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("pmta_reporting") or die(mysql_error());
$newdate = $_REQUEST['date'];
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM address WHERE date=".$newdate) or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Error</th> <th>Date</th> <th>Mail Address</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['code'];
echo "</td><td>";
echo $row['date'];
echo "</td><td>";
echo $row['address'];
echo "</td></tr>";
}
echo "</table>";
// disconnect from the database
mysql_close();
?>
Ok made some changes. I have created 2 files in the directory.
index.php - this contains the date picker and a submit
file2.php - this contains the database query and tables.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/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.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker(({ dateFormat: "yy-mm-dd" }));
});
</script>
</head>
<body>
<form action="file2.php" method="post">
<p>Date: <input type="text" name="datepicker" id="datepicker" /></p>
<div id="displaycontent"> </div>
<input type="submit" value="Submit" />
</form>
</body>
</html>
Then file2.php looks like this:
<?php
// Make a MySQL Connection
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("databasename") or die(mysql_error());
$newdate = $_POST['datepicker'];
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM table_name WHERE date='$newdate'") or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Error</th> <th>Date</th> <th>Mail Address</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['code'];
echo "</td><td>";
echo $row['date'];
echo "</td><td>";
echo $row['address'];
echo "</td></tr>";
}
echo "</table>";
// disconnect from the database
mysql_close();
?>
This allows me to filter by date.
Thanks everyone for your contributions

Categories