I'm creating a web page which has events with different dates which are printed out from my database using php. I want it so the events which have gone past the current date automatically do not show on the page.
I'm using the 'date' type in mySQLi for holding the date and when i'm inserting the date into my database i'm using the code;
<?php
if($db_server){
$eventdate = clean_string($db_server, $_POST['eventdate']);
$timeDate = strtotime($eventdate);
$tempdate = date("Y-m-d", $timeDate);
$query = "INSERT INTO events (eventdate) VALUES ('$tempdate')";
mysqli_query($db_server, $query) or
die("Insert failed. ". mysqli_error($db_server));
$message = "Event Uploaded";
}else{
$message = "Error: could not connect to the database.";
}
?>
Event Date: <input type="event-upload" class="standard" name="eventdate" id="datepicker" />
Here's the code when i'm printing out the date;
<?php
if($db_server){
$query = "SELECT * FROM events";
$result = mysqli_query($db_server, $query) or die(mysqli_error($db_server));
if (!$result) die('Query failed: ' . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
echo $row['eventdate']
}
}
?>
If someone could help me out it and tell me what the right WHERE clause is to use, it would be much appreciated.
$query = "SELECT * FROM events WHERE eventdate >= '".date("Y-m-d")."'";
Is that what you're looking for?
Use this using DATEDIFF function in mysql
select * from `events` where DATEDIFF(`eventdate`,now() ) > 0
Related
I'm trying to create a website where anyone can post anything to it without creating an account, long as its just text. My problem is because every time I start the website and post something. Its sent to the bottom, where oldest posts are at the top and new posts are sent to the top. I want to see the new posts on top instead. This is my first time working with PHP, mySQL and databases in general so my code might look bad. Tell me if more information / code is needed. Thank you for your time.
<?php
function setPosts($conn){
if(isset($_POST['postSubmit'])){
$pid = $_POST['pid'];
$date = $_POST['date'];
$message = $_POST['message'];
$sql= "INSERT INTO post(pid, date ,message) VALUES ('$pid', '$date', '$message');";
$result = mysqli_query($conn, $sql);
}
}
function getPosts($conn){
$sql = "SELECT * FROM post";
$result = mysqli_query($conn, $sql);
while($row = $result->fetch_assoc()){
echo "<div class='post-box'>";
echo $row['date']."<br>";
echo nl2br($row['message'])."<br><br>";
echo "</div>";
}
}
You need to add "ORDER BY" to your "SELECT" to sort it.
$sql = "SELECT * FROM post ORDER BY date DESC";
The "DESC" is there so that new posts will be on top. We'd use "ASC" if we wanted older posts on top.
You need to use ODRER BY clause like below :-
$sql = "SELECT * FROM post ORDER BY date DESC";
Reference:- ODRER BY clause
Note:- Your insersion code is wide open for SQL Injection. Use mysqli prepared statements to prevent from it.
Reference:- mysqli::prepare
You need to sort mysql result by date and order it in descending order.replace mysql query to this
$sql = "SELECT * FROM post SORT BY date order BY DESC";
function getPosts($conn){
$sql = "SELECT date,message FROM post ORDER BY date DESC";
$result = mysqli_query($conn, $sql);
while($row = $result->fetch_assoc()){
echo "<div class='post-box'>";
echo $row['date']."<br>";
echo nl2br($row['message'])."<br><br>";
echo "</div>";
}
}
I've created a page counter, and want to track how many times the user click the page.
So far I can track how many times they click the page, but I want to now set it so when a week is up that it will create a new entry.
My mysql_query look up is base on the user's name, seeing there is more than one user I'm tracking.
This is my code for tracking a user for a selected page:
<?php
include"lib/settings.php";
date_default_timezone_set("America/Los_Angeles");
$track_users_clicks = $_SESSION['username'];
$todays_date = date("m/d/Y H:i:s a");
$query = "SELECT * FROM page_count WHERE `username`=".sql_val($track_users_clicks);
$result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.<br />Query: ".$query."<br />Error: (".mysql_errno().") ".mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$username = $row['username'];
$counter_snippet = $row['counter_snippet'];
$date_time = $row['date_time'];
}//end while
if ($_SERVER['REMOTE_ADDR']){
$query_update = 'UPDATE page_count SET
`counter_snippet` = '.sql_val($counter_snippet + 1).',
`date_time` = '.sql_val($todays_date).'
WHERE `username` = '.sql_val($track_users_clicks);
$result = mysql_query($query_update) or die("<b>A fatal MySQL error occured</b>.<br />Query: ".$query_update."<br />Error: (".mysql_errno().") ".mysql_error());
}
?>
This is so far what I've come up with for tracking a user per week:
<?php
include"lib/settings.php";
date_default_timezone_set("America/Los_Angeles");
//$track_users_clicks = $_SESSION['username'];
$todays_date = date("m/d/Y");
$begin_date = date("m/d/Y");
$end_date = date( "m/d/Y", strtotime($begin_date."+7 day" ) );
$user_log = "trevor.hanes" .$end_date;
$track_users_clicks = "trevor.hanes";
$query_begin = "SELECT * FROM date_time WHERE `username`=".sql_val($track_users_clicks);
$result = mysql_query($query_begin) or die("<b>A fatal MySQL error occured</b>.<br />Query: ".$query_begin."<br />Error: (".mysql_errno().") ".mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$username = $row['username'];
$counter_snippet = $row['counter_snippet'];
$start_date = $row['start_date'];
//$end_date = $row['end_date'];
}
if ($todays_date >= $end_date){
$query_start = 'INSERT INTO date_time (
`username`,
`start_date`,
`end_date`,
`user_log`
) VALUES (
'.sql_val($track_users_clicks).',
'.sql_val($todays_date).',
'.sql_val($end_date).',
'.sql_val($user_log).'
)';
$result = mysql_query($query_start) or die("<b>A fatal MySQL error occured</b>.<br />Query: ".$query_start."<br />Error: (".mysql_errno().") ".mysql_error());
}
else
{
if ($_SERVER['REMOTE_ADDR']){
if ($end_date >= $todays_date){
$query_update = 'UPDATE date_time SET
`counter_snippet` = '.sql_val($counter_snippet + 1).'
WHERE `end_date` = '.sql_val($end_date);
$result = mysql_query($query_update) or die("<b>A fatal MySQL error occured</b>.<br />Query: ".$query_update."<br />Error: (".mysql_errno().") ".mysql_error());
}}}
echo $begin_date;
echo "<BR>";
echo $end_date;
echo "<BR>";
echo $user_log;
?>
So my problem is once I change the date any later than the end date, it just keeps creating new table entries. Instead of creating one new table entry for the new week then updating the hits.
Any thoughts on what I'm doing wrong.
First thing's first: You NEED to be using prepared statements. Prepared statements will prevent malicious code from profoundly impacting your database. For example, somebody could drop your entire table if you had poorly configured user privileges by getting the following text into $_SESSION['username']:
; DROP TABLE page_count;
This looks like a decent tutorial on PDO (most common way to use prepared statements in PHP) at: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
Anyway, to actually answer your question, use a query like the following:
SELECT *, YEARWEEK(date_time) as week,
FROM page_count WHERE `username` = :USERNAME
GROUP BY week;
Documentation for YEARWEEK: http://www.techonthenet.com/mysql/functions/yearweek.php
I have one page (members.php) that post date to another page (results.php). Using the below code, i can successfully get the "to" and "from" variables from the members page.
<?php echo $_POST["to"]; ?>
<?php echo $_POST["from"]; ?>
My problem now is, how can i create a query (in results.php) in order to show filter results only for the dates that are specified at the above variables? Do i need to create an sql connection and sql query too?
If dates are in YYYY-mm-dd format then you can use it as below otherwise you need to change the format.
You can do as below :
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
//$from_date = $_POST['from_date'];
//$to_date = $_POST['to_date'];
$from_date = date("Y-m-d",strtotime('06/10/2015'));
$to_date = date("Y-m-d",strtotime('06/16/2015'));//$_POST['to_date'];
$query = "SELECT * FROM table WHERE from_date >= '".$from_date."' AND to_date <= '".$to_date."'";
// Perform Query
$result = mysql_query($query);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while ($row = mysql_fetch_assoc($result)) {
print_r($row);
}
You should connect to database and compare this two dates:
$dateOne = $_POST["from"];
$dateTwo = $_POST["to"];
If bigger date is 0, then you should always make it the highest date possible to successfully query Data:
if(empty($dateTwo))
{
$dateTwo = date("31-12-Y");
//If $dateTwo is null, than it will be 31/12/2015 otherwise query will now work well
}
Then you should write sql query like this:
"SELECT * FROM `table` where `dateOne` > '$dateOne' and `dateTwo` < '$dateTwo'";
In this case if user wants all dates bigger than dateOne but doesn't check dateTwo, this query will return all data bigger than dateOne and lower than highest date available in current year (In our case it's 31/21/2015).
Its not necessarily creating a new sql connection but just a new query (proposed you have already connected to the database). In my opinion, if you want to display the results between the two dates.
I am not checking for existing or empty values since the dates have been already given.
So:
<?php $start_date = $_POST["from"];
$end_date = $_POST["to"];
//sql will be
$sql = "SELECT * FROM `your_table` WHERE `the_date_column` BETWEEN {$start_date} AND {$end_date}";
?>
Please but doing this use mysqli or PDO connection layer and also try to escape the variables to prevent sql injection or better off, use prepared statements.
SELECT * FROM sales WHERE build_date BETWEEN '$start_date' AND '$end_date';
I have a database field which are
Appt_Datetime (which is call as DateTime in my table)
Svc_ID (which i call ApptType in my table)
I wanted the system to let the customer know that the datetime for the appt type is not available once someone else has book that slot.I have done a lot of research and trying out different codes but to no avail. I've seen answers on stackoverflow that uses PDO but im not so clear about it hence i'd like something to do with mysql. I have been stuck at with this at least few weeks now. Help
This is my call func:
$datetime = $_POST['DateTime'];
$appt = $_POST['ApptType'];
This is the query i last tried out but still is not working:
//Define query
$vquery = "SELECT * FROM Appointment where Appt_DateTime='$datetime' && Svc_ID='$appt'";
//Run Query
$result = mysql_query($query, $conn);
$row = mysql_fetch_assoc($result);
if($row==1)
{
echo "Date in not available";
}
else if($row==0)
{
$query = "INSERT INTO Appointment (Client_ID,Svc_ID,Appt_DateTime)
VALUES ('$_POST[ClientID]','$_POST[ApptType]','".date('Y-m-d H:i:s', strtotime($_POST[DateTime]))."')";
mysql_query($query,$conn);
}
Hint:
change this to $result = mysql_query($query, $conn); to $result = mysql_query($vquery, $conn);
at the time you are using $conn you do not have $query it is $vquery:
$result = mysql_query($vquery, $conn);
And as suggested above in comments better use mysqli or PDO.
you can try this condition..
//Define query
$vquery = "SELECT * FROM Appointment where Appt_DateTime='$datetime' && Svc_ID='$appt'";
//Run Query
if($result = mysql_query($vquery, $conn)){
//$row = mysql_fetch_assoc($result);
if(mysql_num_row($result)>0)
{
echo "Date in not available";
}
else
{
/* $query = "INSERT INTO Appointment (Client_ID,Svc_ID,Appt_DateTime)
VALUES ('$_POST[ClientID]','$_POST[ApptType]','".date('Y-m-d H:i:s', strtotime($_POST[DateTime]))."')";
mysql_query($query,$conn); */
echo "insert";
}
}else{
echo mysql_error();
}
I am an amateur programmer and have recently been facing a challenge.
I am trying to select a data between range of dates but despite numerous attempts have been unsuccessful. Can someone help me with the code of pulling up data between date ranges.
My code is:
<?php
$tdate = $_POST['toDate'];
$fdate = $_POST['fromDate'];
mysql_connect("localhost","user","pass") or die("Couldn't connect!");
mysql_select_db("db_name") or die("Couldn't find db");
$data = mysql_query("SELECT * FROM db_table BETWEEN saledate '$tdate' AND '$fdate' ");
$result = mysql_fetch_array($data);
if (!$result) {
echo "No result";
} else {
echo $result;
}
?>
You shouldn't do Query like that. Use PDO.
Regarding your SQL is wrong. The right is:
$data = mysql_query("SELECT * FROM db_table WHERE saledate BETWEEN '$tdate' AND '$fdate' ");
You sql should be this
SELECT * FROM db_table WHERE saledate BETWEEN $tdate AND $fdate
In your code, instead of
$result = mysql_fetch_array($data);
if (!$result) {
echo "No result";
} else {
echo $result;
}
write the following code.
while($result=mysql_fetch_array($data))
{
echo $result['Fieldname1'];
......
......
echo $result['Fieldnamen'];
}
In place of fieldname, write the fields from your table. The fields you want to display.