Post data in database without refreshing PHP Page - php

I am working with two php file. The first file contains a search engine that outputs the results in the second php file. This second php file is displayed in an iframe just underneath the search engine of the first php file. this file also contains data that needs to be submitted using post. I can submit the form and redirect it to a 3rd php file. But I dont want to go away from the current page. So far what I can do is to call an isset function on the same page and fire the insert command to my table. But it refreshes the 2nd php file. Refreshing will reset the search values passed from the 1st php file which is not good. Please help
This is my 2nd php file:
<!DOCTYPE html>
<html>
<head>
<title>RFC System</title>
<script src="jquery-1.12.4.js"></script>
<link rel="stylesheet" type="text/css" href="style2.css">
<link rel="stylesheet" type="text/css" href="modal.css">
</head>
<body>
<?php
require ("../funcs.php"); site_security();
set_error_handler ("my_error_handler");
set_time_limit(0);
date_default_timezone_set ("Asia/Manila");
require("../connmysql.php");
$session_user_id = $_SESSION["USERCID"];
$session_branch = $_SESSION["BRANCHCODE"];
$branchname=$_POST['branchname'];
$empbio=$_POST['empbio'];
$dtrdate_from=$_POST['dtrdate_from'];
$dtrdate_to=$_POST['dtrdate_to'];
##########HELP HERE!
if(isset($_POST['reason'])){
#save to database without refreshing the page
}
#####################
if((empty($branchname)) || (empty($empbio)) || (empty($dtrdate_from)) || (empty($dtrdate_to))){
echo "<font color='#FF0000'><b>Please fill-in all fields to start search</b></font>";
}else{
$startDate = DateTime::createFromFormat("Y/m/d","$dtrdate_from",new DateTimeZone("Asia/Manila"));
$endDate = DateTime::createFromFormat("Y/m/d","$dtrdate_to",new DateTimeZone("Asia/Manila"));
$periodInterval = new DateInterval( "P1D" ); // 1-day, though can be more sophisticated rule
$period = new DatePeriod( $startDate, $periodInterval, $endDate );
$queryname=mysqli_query($conn,"select a.nsemp_fname,a.nsemp_mname,a.nsemp_lname,a.nsemp_sufixname,a.nsemp_empid,a.nsemp_bionum,a.nsemp_brcode from rfc_prf_nsemp a where a.nsemp_bionum=12476")or die();
while($row=mysqli_fetch_array($queryname)){
$fname=$row[0];
$mname=$row[1];
$lname=$row[2];
$suffix=$row[3];
$empid=$row[4];
$bionum=$row[5];
$brcode=$row[6];
}
echo"<hr/>
<h3><b>Name:</b>$fname $mname[0] $lname $suffix<br/>
<b>Employee No:</b> $empid<br/>
<b>Branch:</b> $brcode<br/></h3>
<table class='x'><tr>";
foreach($period as $date){
$x = $date->format("Y-m-d");
$day = date('l', strtotime($x));
if($day=="Sunday"){$background="#00e673";}else if($day=="Saturday"){$background="#ffff99";}else{$background="#ffffff";}
echo"<td height='150px' style='border-style: solid; background:$background'>
<form method='post' action='#'>
<b><font color='#1a1aff'>$x<br/>$day</font></b><br/><br/>";
$query=mysqli_query($conn,"select dtr_time,(CASE in_or_out WHEN 0 THEN 'IN' WHEN 1 THEN 'OUT' END) AS status,datacid from rfc_bio_dtr where dtr_date='$x' and empbio='12476';")or die(mysqli_error());
$check="";
while($row=mysqli_fetch_array($query)){
echo "$row[0] $row[1] <br/>";
$check .=$row[1];
}
if(preg_match('(IN)', $check) && preg_match('(OUT)', $check)) { echo" ";}else{
$queryReason=mysqli_query($conn,"select tk_reason_id,tk_reason_desc from rfc_timekeeping_param;")or die();
echo "<br/><br/>Remarks:<select name='' id=''>";
while($row=mysqli_fetch_array($queryReason)){
echo "<option value='$row[0]'>$row[1]</option>";
}
echo"</select><br/>Notes:<br/><textarea></textarea><input type='submit' value='save' name='reason' id='reason' class='totobutton'>";
}
echo"</form></td>";
}
}
?>
</body>
Here is an updated code using jquery/ajax. There's a problem with the next table data, they dont get submitted. only the first table data gets submitted:
<!DOCTYPE html>
<html>
<head>
<title>RFC System</title>
<script src="jquery-1.12.4.js"></script>
<link rel="stylesheet" type="text/css" href="style2.css">
<link rel="stylesheet" type="text/css" href="modal.css">
<script>
$(function () {
$('#myform').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'savetodb.php',
data: $('#myform').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
</head>
<body>
<?php
require ("../funcs.php"); site_security();
set_error_handler ("my_error_handler");
set_time_limit(0);
date_default_timezone_set ("Asia/Manila");
require("../connmysql.php");
$session_user_id = $_SESSION["USERCID"];
$session_branch = $_SESSION["BRANCHCODE"];
$branchname=$_POST['branchname'];
$empbio=$_POST['empbio'];
$dtrdate_from=$_POST['dtrdate_from'];
$dtrdate_to=$_POST['dtrdate_to'];
if((empty($branchname)) || (empty($empbio)) || (empty($dtrdate_from)) || (empty($dtrdate_to))){
echo "<font color='#FF0000'><b>Please fill-in all fields to start search</b></font>";
}else{
$startDate = DateTime::createFromFormat("Y/m/d","$dtrdate_from",new DateTimeZone("Asia/Manila"));
$endDate = DateTime::createFromFormat("Y/m/d","$dtrdate_to",new DateTimeZone("Asia/Manila"));
$periodInterval = new DateInterval( "P1D" ); // 1-day, though can be more sophisticated rule
$period = new DatePeriod( $startDate, $periodInterval, $endDate );
$queryname=mysqli_query($conn,"select a.nsemp_fname,a.nsemp_mname,a.nsemp_lname,a.nsemp_sufixname,a.nsemp_empid,a.nsemp_bionum,a.nsemp_brcode from rfc_prf_nsemp a where a.nsemp_bionum=12476")or die();
while($row=mysqli_fetch_array($queryname)){
$fname=$row[0];
$mname=$row[1];
$lname=$row[2];
$suffix=$row[3];
$empid=$row[4];
$bionum=$row[5];
$brcode=$row[6];
}
echo"<hr/>
<h3><b>Name:</b>$fname $mname[0] $lname $suffix<br/>
<b>Employee No:</b> $empid<br/>
<b>Branch:</b> $brcode<br/></h3>
<table class='x'><tr>";
foreach($period as $date){
$x = $date->format("Y-m-d");
$day = date('l', strtotime($x));
if($day=="Sunday"){$background="#00e673";}else if($day=="Saturday"){$background="#ffff99";}else{$background="#ffffff";}
echo"<td height='150px' style='border-style: solid; background:$background'>
<b><font color='#1a1aff'>$x<br/>$day</font></b><br/><br/>";
$query=mysqli_query($conn,"select dtr_time,(CASE in_or_out WHEN 0 THEN 'IN' WHEN 1 THEN 'OUT' END) AS status,datacid from rfc_bio_dtr where dtr_date='$x' and empbio='12476';")or die(mysqli_error());
$check="";
while($row=mysqli_fetch_array($query)){
echo "$row[0] $row[1] <br/>";
$check .=$row[1];
}
if(preg_match('(IN)', $check) && preg_match('(OUT)', $check)) { echo" ";}else{
$queryReason=mysqli_query($conn,"select tk_reason_id,tk_reason_desc from rfc_timekeeping_param;")or die();
?>
<form id="myform">
<select name="reason" value="reason">
<?php
while($row=mysqli_fetch_array($queryReason)){
echo "<option value='$row[0]'>$row[1]</option>";
}
?></select>
<textarea name="notes" value="notes"></textarea><br>
<input name="submit" type="submit" value="Submit">
</form><?php
}
echo"</td>";
}
}
?>
</body>
Here's savetodb.php
<?php
require("../connmysql.php");
$fname=$_POST['reason'];
$lname=$_POST['notes'];
$queryx=mysqli_query($conn,"insert into test (fname,lname) values ('$fname','$lname');")or die(mysqli_error());
?>

You already have jQuery loaded, so start AJAX from an onclick handler and put the save in a totally different PHP file (one that only outputs "OK" or "ERROR: something." See http://pqxb.qr.ai for a relevant tutorial.

Related

start end date & dropdown menu from mysql in one html page

I am trying to make a html or php page (for some own learning process) which can input 3 selection and then display there results in next page.
1- input Start Date
2- input End Date
3- Show Service Name in drop down menu via mysql query to get services names from the table
So far I have managed to get the start and end table and drop down menu which successfully query the services table and shows the name, but the problem is that when i click submit i can see the results of start and end date but i am unable to see how can i add services selection in the posting.
This is my code.
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
$("#start_datepicker").datepicker();
$("#end_datepicker").datepicker();
});
</script>
</head>
<body style="font-size:62.5%;">
<form action="test.php" method="post">
Start Date: <input type="text" name="startdate" id="start_datepicker"> <br />
End Date: <input type="text" name="enddate" id="end_datepicker"><br />
<select name="srvname">
<?php
$conn = new mysqli('localhost', 'root', 'SQLPASS', 'radius')
or die ('Cannot connect to db');
$result = $conn->query("select srvname name from rm_services");
while ($row = $result->fetch_assoc()) {
echo "<option value=\"" . $row["id"] . "\">" . $row["name"] . "</option>";
}
?>
</select>
<input type="submit" value="Submit:">
</form>
</body>
</html>
and this is test.php which will per form action shows the date
<?php
$STARTDATE = $_POST['startdate'];
$ENDDATE = $_POST['enddate'];
$SRVNAME = $_POST['srvname']; //gets the value -> $row["id"]
echo "<h2>You have entered the following information:</h2>";
echo "<pre>$STARTDATE</pre> ";
echo "<pre>$ENDDATE</pre>";
echo "<pre>$SRVNAME</pre>";
?>
This one should work, and for the future: if you post something on stackoverflow, please post formatted code, it's way easier to edit and especially to read it...
your index.php or whatever...
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
$("#start_datepicker").datepicker();
$("#end_datepicker").datepicker();
});
</script>
</head>
<body style="font-size:62.5%;">
<form action="test.php" method="post">
Start Date: <input type="text" name="startdate" id="start_datepicker"> <br />
End Date: <input type="text" name="enddate" id="end_datepicker"><br />
<select name="srvname">
<?php
$conn = new mysqli('localhost', 'root', 'SQLPASS', 'radius')
or die ('Cannot connect to db');
$result = $conn->query("select id, name from rm_services");
while ($row = $result->fetch_assoc()) {
echo "<option value=\"" . $row["id"] . "\">" . $row["name"] . "</option>";
}
?>
</select>
<input type="submit" value="Submit:">
</form>
</body>
</html>
your test.php
<?php
$STARTDATE = $_POST['startdate'];
$ENDDATE = $_POST['enddate'];
$SRVNAME = $_POST['srvname']; //gets the value -> $row["id"]
echo "<h2>You have entered the following information:</h2>";
echo "<pre>$STARTDATE</pre> ";
echo "<pre>$ENDDATE</pre>";
echo "<pre>$SRVNAME</pre>";
?>
I didn't test it, but actually it should work...

Sum time from datetime

I have an table in sql the type is datetime y m d h i s
and im using mid in php to get the time alone and the date alone like this
mid(tablename,1,10) to get the date only like this 'y m d'
and useing
mid(tablename,12,8) to get the time only like this 'H:i:s'
and this is code explane what i did
<html>
<head>
<title>ss</title>
</head>
<body>
<form method='post' action='<?php $_SERVER['SELF'];?>'>
<input type='submit' name='submit' />
</form>
<?
include("config");
$submit = $_POST['submit'];
$getdata1= mysql_query("select checktime from calls");
if(isset($submit))
{
while($getdata= mysql_fetch_array($getdata1))
{
echo "<input type='text' name='text' value='mid($getdata[1],12,8)'";
}
}
?>
</body>
</html>
now I get the result like this
08:00:00
08:10:00
07:00:51
and so on
What I need to sum the result as
date("d H:i:s",strtotime(all result from fetch array))
so I tried this
<html>
<head>
<title>ss</title>
</head>
<body>
<form method='post' action='<?php $_SERVER['SELF'];?>'>
<input type='submit' name='submit' />
</form>
<?
include("config");
$submit = $_POST['submit'];
$getdata1= mysql_query("select checktime from calls");
if(isset($submit))
{
while($getdata= mysql_fetch_array($getdata1))
{
echo "<input type='text' name='text' value='mid($getdata[1],12,8)'";
for($i=0;$i<5;$i++)
{
$i+= strtotime($getdata[0]);
}
}
echo $i;
}
?>
</body>
</html>
but I have only the last result
so I tried to do it in sql query like this
<html>
<head>
<title>ss</title>
</head>
<body>
<form method='post' action='<?php $_SERVER['SELF'];?>'>
<input type='submit' name='submit' />
</form>
<?
include("config");
$submit = $_POST['submit'];
$getdata1= mysql_query("select unix_timestamp(mid(checktime,12,8)) from calls");
if(isset($submit))
{
while($getdata= mysql_fetch_array($getdata1))
{
echo "<input type='text' name='text' value='mid($getdata[1],12,8)'";
for($i=0;$i<5;$i++)
{
$i+= $getdata[0];
}
}
echo $i;
}
?>
</body>
</html>
and the result I get at not from 1970-1-1, but I get at from mid(checktime,1,10), so what I want is to sum the result thats comes out like this:
H:i:s
from the whole fetch.
I mean, how can I sum the result to come out like this:
08:00:00
08:10:00
07:00:51
in one variable?
If I understand well to you question, here is small example how you can sum up and format time as you required.
$times = ['15:00:00', '08:10:00', '07:00:51'];
$date = new \DateTime;
$alteredDate = new \DateTime;
foreach ($times as $time) {
$parts = explode(':', $time);
$alteredDate->add(new \DateInterval(sprintf('PT%dH%dM%dS', $parts[0], $parts[1], $parts[2])));
}
echo $alteredDate->diff($date)->format('%a %h:%i:%s');

php form that requests data based on user select

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);
?>
}

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

Form not recognizing post variables

I have a simple html form and some php that input the POST variables into a mysql database. However, I noticed that the form would not input the data when
if (isset($_POST['submit'])){
insert stuff in here
}
was included. I then removed the if statement above and ran the code. All of the variables were imputed except the ones from the form using POST (ex $_POST['var1']). It seems like the POST variables are not being recognized and I dont know what's wrong.
ALL CODE:
<?php session_start(); ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
<script type='text/javascript' src='http://twitter.github.com/bootstrap/1.4.0/bootstrap-modal.js'></script>
<link rel="stylesheet" href="../css/bootstrap.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../css/basic.css" type="text/css" media="screen" />
</head>
<body>
<?php include '../css/bar.php'; ?>
<div id='content'>
<?php include '../nav.php';
?>
<?php
if (isset($_POST['submit'])){
include '../connect.php';
$question=mysql_real_escape_string($_POST['question']);
$detail=mysql_real_escape_string($_POST['detail']);
$date=date("d M Y");
$time=time();
$user=$_SESSION['id'];
$put=mysql_query("INSERT INTO questions VALUES ('','$question','$detail','$date','$time','$user','subject','0')");
$result=mysql_query("SELECT * FROM questions WHERE user='$user' AND time='$time'");
while ($row = mysql_fetch_assoc($result)){
$q=$row['id'];
}
}
?>
<form method='POST' action='question.php?q=<?php echo $q ?>'>
<p>Question:</p>
<p><input type='text' name='question' id='question' maxlength='200'></p>
<p>Add some detail (optional):</p>
<p><textarea id='detail' name='detail' ></textarea></p>
<p>Tags:</p>
<p><input type='submit' value='submit' name='submit'></p>
</form>
</div>
<?php include '../footer.php'; ?>
</body>
</html>
TESTPAGE:
<?php
include 'connect.php';
if (isset($_POST['submit'])){
$hhh=mysql_real_escape_string($_POST['hhh']);
$put=mysql_query("INSERT INTO questions VALUES ('','$hhh','','','','','','')");
}
?>
<form action='test.php' method='post'>
<input type='text' name='hhh'>
<input type='submit' name='submit' value='submit'>
</form>
You have two PHP pages - ask.php and question.php. I (guess)think the ask.php is used to store questions and other details and you want to open a question.php with question id.
ask.php
<?php session_start(); ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
<script type='text/javascript' src='http://twitter.github.com/bootstrap/1.4.0/bootstrap-modal.js'></script>
<link rel="stylesheet" href="../css/bootstrap.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../css/basic.css" type="text/css" media="screen" />
</head>
<body>
<?php include '../css/bar.php'; ?>
<div id='content'>
<?php
include '../nav.php';
/*--- If submit button is pressed ---- */
if (isset($_POST['submit']))
{
include '../connect.php';
$question=mysql_real_escape_string($_POST['question']);
$detail=mysql_real_escape_string($_POST['detail']);
$date=date("d M Y");
$time=time();
$user=$_SESSION['id'];
/* SELECT column names you want to use with INSERT statement */
$put=mysql_query("INSERT INTO questions
(`question`,`detail`,`date`,`time`,`user`,`subject`,`name_of_last_col` )
VALUES
('$question','$detail','$date','$time','$user','subject','0')");
//for debug purpose
if($put)
{
echo "Record added";
}
else
{
echo "Can't add record " . mysql_error();
}
}
/*----- End submit block -----------*/
/*----List the questions and select it----------*/
$time=time();
$user=$_SESSION['id'];
//I think this wont work. Try to remove time comparison from the SELECT statement.
$result=mysql_query("SELECT * FROM questions WHERE `user`='$user' AND `time`='$time'");
//$result=mysql_query("SELECT * FROM questions WHERE `user`='$user'");
if($result)
{
echo "<table>";
while($row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>$row[question]</td>";
echo "<td><a href='question.php?qid=$row[id]'>Show a question</a></td>";
echo "</tr>";
}
echo "</table>";
}
else
{
echo "No questions!!!";
}
?>
<form method='POST' action="ask.php">
<p>Question:</p>
<p><input type='text' name='question' id='question' maxlength='200'></p>
<p>Add some detail (optional):</p>
<p><textarea id='detail' name='detail' ></textarea></p>
<p>Tags:</p>
<p><input type='submit' value='submit' name='submit'></p>
</form>
question.php should be:
<?php
$qid=$_GET["qid"];
echo "$qid is selected...";
?>
You may split code into two PHP pages - one for save records and another to list and select rows.
addquestion.php
<?php
session_start();
if(isset($_POST['submit']))
{
mysql_connect("localhost","user","password") or die(mysql_error());
mysql_select_db("your_db_name") or die(mysql_error());
$question=mysql_real_escape_string($_POST['question']);
$detail=mysql_real_escape_string($_POST['detail']);
$date=date("d M Y");
$time=time();
$user=$_SESSION['id'];
$put=mysql_query("INSERT INTO questions
(`question`,`detail`,`date`,`time`,`user`,`subject`,`name_of_last_col` )
VALUES
('$question','$detail','$date','$time','$user','subject','0')");
//for debug purpose
if($put)
{
echo "Record added";
}
else
{
echo "Can't add record " . mysql_error();
}
}
?>
<form method='post' action="addquestion.php">
<p>Question:</p>
<p><input type='text' name='question' id='question' maxlength='200'></p>
<p>Add some detail (optional):</p>
<p><textarea id='detail' name='detail' ></textarea></p>
<p>Tags:</p>
<p><input type='submit' value='submit' name='submit'></p>
</form>
questionlist.php
<?php
session_start();
$user=$_SESSION['id'];
mysql_connect("localhost","user","password") or die(mysql_error());
mysql_select_db("your_db_name") or die(mysql_error());
$result=mysql_query("SELECT * FROM questions WHERE `user`='$user'");
if($result)
{
echo "<table>";
while($row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>$row[question]</td>";
echo "<td><a href='question.php?qid=$row[id]'>Show a question</a></td>";
echo "</tr>";
}
echo "</table>";
}
else
{
echo "No questions!!!";
}
?>

Categories