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
Related
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.
update
Can anyone explain to me why I am getting duplicate messages instead of one?
how can I change my code so that when I type a comment and press "Comment" button, it will only display one message instead of duplicates! When I have one comment boxes it doesn't show duplicate comments, but if I have more than one then it starts duplicating!
COMMENT.INC.PHP
include 'cdbh.inc.php';
function setComments($con)
{
if (isset($_POST['commentSubmit'])) {
$uid = mysqli_real_escape_string($con,$_POST['uid']);
$date = mysqli_real_escape_string($con,$_POST['date']);
$message = mysqli_real_escape_string($con,$_POST['message']);
$sql = "INSERT INTO comments (uid, date, message) VALUES ('$uid','$date','$message')";
$result = mysqli_query($con,$sql);
}
}
function getComments($con)
{
$sql = "SELECT * FROM comments";
$result = mysqli_query($con,$sql);
while ($row=mysqli_fetch_assoc($result)) {
echo $row['uid'];
echo ":";
echo $row['message']."<br><br>";
}
}
page code
<?php
date_default_timezone_set('America/Los_Angeles');
include 'comment.inc.php';
include("connection.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="comment.css" rel ="stylesheet">
</head>
<body>
<?php
$sql="Select * from tbl_images";
$result=mysqli_query($connection,$sql);
while ($row=mysqli_fetch_array($result)) {
?>
<img src="images/<?php echo $row['images_name'] ?>" width="200px" height="200px">
<?php
echo "<form method ='POST' action ='".setComments($con)."'>
<input type ='hidden' name ='uid' value='unknown'>
<input type ='hidden' name ='date' value='".date('Y-m-d H:i:s')."'>
<textarea name='message'></textarea>
<button type ='submit' name='commentSubmit'>Comment</button>
</form>";
}
getComments($con);
?>
</body>
</html>
Maybe you are submiting all your forms instead of one..
check your database in order to know from what img comes each message.
If you have other code like javascript, you should post it.
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...
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);
?>
}
i have a website i am constructing for a school project, in which i already have various webpages where i get tabular data from my database through the use of While and Foreach.
But on this page in question, i am attempting to retrieve data from various tables, in order for a user to choose a category, and a text and submit.
But for some reason it isn't outputting any data. If i attempt with only one table and without using the table.field method, and only typing the fields, it works.
But from what i know, to retrieve from various tables i have to do so.
Can annione help me out on this?
<html>
<head>
<script type="text/javascript" >
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<?php
mysql_connect("localhost","root","") or die("problema na conexao");
mysql_select_db("trabalho1");
$query = "SELECT texto.titulo,texto.ID,categoria.categoria,categoria.id FROM categoria,texto";
$results = mysql_query($query) or die(mysql_error());
echo"<center>";
echo "<table border='2'>\n";
echo "<form id='formulario' name='post' method='post' onsubmit='return validar(this) action='../inserir/inseretexto.php>'";
echo "<button type='submit'>Submeter</button>";
echo "<tr><td colspan ='2'>Historico de Newsletters</td><td colspan='2'>Enviar Newsletter</td></tr>";
echo "<tr><td colspan='2'>Texto </td><td colspan='2'>Categoria</td></tr>";
while ($row = mysql_fetch_assoc($results)) {
foreach ($row as $campo=>$valor) {
if ($campo == "texto.titulo") {
echo "<tr><td>'".$valor."'</td>";
}
if ($campo == "texto.ID") {
echo "<td><input type='radio' name='nome' value='".$valor."'></td></tr>";
}
if ($campo == "categoria.categoria") {
echo "<td>'".$valor."'</td>";
}
if ($campo=="categoria.id") {
echo "<td><input type='radio' name='nome' value='".$valor."'></td></tr>";
}
}
}
echo "</form>";
echo "</table>";
echo "</center>";
?>
</body>
</html>
Added: Since both tables have a field called id, it won't let me simply put the field names, i have to also put the table name like i did. And yes, i have verified and both tables are populated with data, they work fine on other pages.
This is what I suggest (I didn't consider much code optimization).
<?php
$data = array();
mysql_connect('localhost', 'root', '') or die('problema na conexao');
mysql_select_db('trabalho1');
// Use the same field-names/aliases: id, info
$query = 'SELECT ID AS id, titulo AS info FROM texto';
$results = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($results)) {
$data[] = $row;
}
// Use the same field-names/aliases: id, info
$query = 'SELECT id, categoria AS info FROM categoria';
$results = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($results)) {
$data[] = $row;
}
?>
<html>
<head>
<script type="text/javascript">
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<center>
<table border='2'>
<form id='formulario' name='post' method='post' onsubmit='return validar(this) action='../inserir/inseretexto.php>
<tr><td colspan ='2'><button type='submit'>Submeter</button></td></tr>
<tr><td colspan ='2'>Historico de Newsletters</td><td colspan='2'>Enviar Newsletter</td></tr>
<tr><td colspan='2'>Texto </td><td colspan='2'>Categoria</td></tr>
<?php
foreach ($data as $row) {
echo '<td><input type="radio" name="nome" value="' . $row['id'] . '></td></tr>' .
'<tr><td>' . $row['id'] . '</td>';
}
?>
</form>
</table>
</center>
</body>
</html>
PS: Read about my response about double quotations. Should I use curly brackets or concatenate variables within strings?