I have a table message, in which fields are: id,username,message,lastdate. I want to compare from these dates (which are in my table) to current date. If difference is 30 days then respected username should be show in admin page.
I tried for date difference, but its not working.
<?php
include("connection.php");
$queryd=mysql_query("select * from message") or die(mysql_error());
while($resultd=mysql_fetch_array($queryd))
{
extract($resultd);
$date1=date('Y-m-d');
$date2=$lastdate;
$diff=date_diff($date2,$date1);
echo $diff->format("%R%a days");
}
?>
Also I tried from this code. But nothing happend
<?php
include("connection.php");
$queryd=mysql_query("select * from message") or die(mysql_error());
while($resultd=mysql_fetch_array($queryd))
{
extract($resultd);
$date1=date('Y-m-d');
$date2=$lastdate;
$query12=mysql_query("SELECT username,DATEDIFF($date1,$date2) FROM message WHERE DATEDIFF($date1,$date2)<30") or die(mysql_error());
while($result12=mysql_fetch_array($query12))
{
if($result12)
echo $username;
else
echo"record not";
}
}
?
My third solution is here. I think it is working. But It is repeating values.
<?php
include("connection.php");
$queryd=mysql_query("select * from message") or die(mysql_error());
while($resultd=mysql_fetch_array($queryd))
{
extract($resultd);
$date1=date('Y-m-d');
$date2=$lastdate;
$days = (strtotime($date2) - strtotime($date1)) / (60 * 60 * 24);
$result123=mysql_query("select username from message where '$days'<30");
while($query123=mysql_fetch_array($result123))
{
if($query123)
echo $username." ".$days."<br>";
else
echo mysql_error();
}
}
?>
You can do this date comparison inside your MySQL DBMS.
Try this query:
SELECT username, message FROM message WHERE lastdate <= CURDATE() - INTERVAL 30 DAY
It should return just the rows of interest.
Related
There are many similiar questions but I don't have any error, where I need to do changes.
I have put alert boxes in my code but non are appearing.
Here is my code-
if(isset($_POST['submit'])){
$test= "select * from stable where Email = '$Email'";
$queryResult = $conn->query($test);
$foundRows = $queryResult->num_rows;
if($foundRows >= 1)
$mailerr="Email already register";
else {
header("location:student.php?id=".$row['id']);
$sql = "INSERT INTO stable
(Firstname,Lastname,DOB,Email,Phno,
Gender,Address,City,ZipCode,State,Country,
Hobbies,Course,id,Time,Date,IP)
VALUES('$Firstname','$Lastname','$Dob','$Email',
'$Phno','$Gender','$Address','$City','$Zipcode',
'$State','$Country','$Hobby','$Course','',
'$Time','$date','$IP')";
if($conn->query($sql))
?>
<script> alert('Data Inserted successfully');
window.location.href='student.php?id=<?php echo $id;?>' </script>
<?php
}
}
You can wrap the script tag with all the js in string and echo it. it will work
if($conn->query($sql)){
echo "<script> alert('Data Inserted successfully')window.location.href='student.php?id="+$id+"</script>";
}
Try this:
if(isset($_POST['submit'])){
$test= "select * from stable where Email = '$Email'";
$queryResult = $conn->query($test);
$foundRows = $queryResult->num_rows;
if($foundRows >= 1)
$mailerr="Email already register";
else {
header("location:student.php?id=".$row['id']);
$sql = "INSERT INTO stable
(Firstname,Lastname,DOB,Email,Phno,
Gender,Address,City,ZipCode,State,Country,
Hobbies,Course,id,Time,Date,IP)
VALUES('$Firstname','$Lastname','$Dob','$Email',
'$Phno','$Gender','$Address','$City','$Zipcode',
'$State','$Country','$Hobby','$Course','',
'$Time','$date','$IP')";
if($conn->query($sql)){
echo "<script type='text/javascript'>alert('Data Inserted successfully');
window.location.href='student.php?id=".$id."';
</script>";
}
}
}
How can I pick a single date from my date range picker?
<script>
$(document).ready(function(){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function(){
$("#from_date").datepicker();
$("#to_date").datepicker();
});
$('#filter').click(function(){
var from_date = $('#from_date').val();
var to_date = $('#to_date').val();
if(from_date != '' && to_date != '')
{
$.ajax({
url:"filtertable.php",
method:"POST",
data:{from_date:from_date, to_date:to_date},
success:function(data)
{
$('#order_table').html(data);
}
});
}
else
{
alert("Please Select Date");
}
});
});
</script>
here's my query coming from the date range picker:
query = "SELECT *
FROM gsm2 WHERE setTime BETWEEN '".$_POST["from_date"]."' AND
'".$_POST["to_date"]."'
If u I try to select 2 same dates it doesn't work because of this
$query = "SELECT *
FROM gsm2 WHERE setTime BETWEEN '".$_POST["from_date"]."' AND
'".$_POST["to_date"]."' ";
I need to add a statement which is
`$query ="SELECT *
FROM gsm2 WHERE setTime = '".$_POST["from_date"]."' OR
'".$_POST["to_date"]."' ";
how can I add this condition to the old query?
Instead of between you can just do the manual:
SELECT *
FROM gsm2
WHERE setTime >= :fromTime AND setTime <= :toTime
Notice how I'm using placeholders there? You should too, and also use prepared statements.
In practice if you are using MySQLi you could do:
$db = mysqli_connect(...); //Your connection
$stmt = $db->prepare("SELECT * FROM gsm2 WHERE setTime >= ? AND setTime <= ?");
$from = filter_input(INPUT_POST, "from_date");
$to = filter_input(INPUT_POST, "to_date");
$stmt->bind_param("ss", $from, $to);
$stmt->execute();
$res = $stmt->get_result();
// Do things like $res->fetch_assoc or similar here
Note that if your $_POST data are dates but your SQL fields are DATETIME then you might need to do some sort of casting e.g. do WHERE DATE(setTime) >= ? AND DATE(setTime) <= ?
I may be wrong (as I'm not equipped to test it right now), but this should work:
$query = "SELECT *
FROM gsm2 WHERE setTime BETWEEN ".$_POST['from_date']." AND ".$_POST['to_date'].";
Going by the assumption that your initial query was right, but your PHP code was throwing up some errors as you are using loads of (' and ")'s.
Mainly posting to point out that you are accepting user input and throwing it straight into a SQL query. I am honestly surprised that in 2018 on StackOverflow, so many users in this category are placing PHP input variables directly into a SQL query and then executing it without checking the input to ensure that it is valid first.
Input such as 1; DROP TABLE gsm2; could have the potential to delete your entire table. I'm not sure what kind of server-side firewalls are in place to deal with this type of attack, but it's terrible practice all the same.
I want to display an alert box showing a message with PHP. If I not use alert box I get the right answer such "update subject set semester=2 where id=171 ". But after I change into alert box the answer i get in the alert box only "update subject set $f=$data where id=$did" and it does not update in database.
Here is my PHP code:
if ($tag == 2) {
$query = '<script type=text/javascript> alert("update subject set $f=$data where id=$did")</script>';
$result = mysql_query($query);
print "$query";
}
Change the quotations. Learn the difference between single and double quotes. Also, you can't update using that which is an invalid query with Javascript statement. Instead use:
if ($tag == 2) {
$query = "update subject set $f=$data where id=$did";
$result = mysql_query($query);
echo "<script type=text/javascript>alert('$query')</script>";
}
Note : mysql_ extensions are deprecated, use mysqli or PDO
What you are passing to the deprecated mysql_query function was not valid sql and would cause an error, I suspect you were trying something along these lines?
if ($tag == 2) {
$sql="update `subject` set `$f`='$data' where `id`='$did'";
$query = '<script type=text/javascript> alert('$sql')</script>';
$result = mysql_query($sql);
echo $query;
}
If you want a success message you should do:
if ($tag == 2) {
$query = 'update subject set $f=$data where id=$did")';
$result = mysql_query($query);
if($result)
echo "<script type=text/javascript> alert('message')</script>";
}
}
I have Remind_Date option in my table and I want to compare Remind_Date with Current_Date. If both are equal then alert will pop up on body on load showing corresponding member name. and also I want to develop cases for the alert. Alert will pop up 2 days or 3 days before remind date.
$now=date("Y/m/d");
$sql = "select RemindDate from payment ";
$result = mysql_query($sql) or die(mysql_error());
while($rowval2 = mysql_fetch_array($result))
{
$RemindDate=$rowval2['RemindDate'];
}
$sql = "select MemName from payment where $RemindDate = '".$now."' ";
$result = mysql_query($sql) or die(mysql_error());
while($rowval2 = mysql_fetch_array($result))
{
$MemName=$rowval2['MemName'];
}
?>
</script>
<body onload= "alert('<?php echo $MemName ; ?>')">
I want to select MySQLi records between a startdate and enddate so I have a JS script that allows me to enter dates (using HTML datebox type inputs) which I pass to a PHP script using JQuery's $.post method. My JS code is:
startDate = new Date(document.getElementById("fromDate").value);
startDate = new Date(startDate.getUTCFullYear(),startDate.getUTCMonth(), startDate.getUTCDate(), startDate.getUTCHours(), startDate.getUTCMinutes(), startDate.getUTCSeconds());
endDate = new Date(document.getElementById("toDate").value);
endDate = new Date(endDate.getUTCFullYear(), endDate.getUTCMonth(), endDate.getUTCDate(), endDate.getUTCHours(), endDate.getUTCMinutes(), endDate.getUTCSeconds());
$.post("DBQuery.php", {
startdate: startDate,
enddate: endDate,
},
function (output) {
var result = JSON.parse(output);
$('#PHPStartDate').html(result.startdate).show();
$('#PHPEndDate').html(result.enddate).show();
});
My PHP code is:
$startdate = date('Y-m-d h:i:s',strtotime($_POST["startdate"]));
$enddate = date('Y-m-d h:i:s',strtotime($_POST["enddate"]));
$con = mysqli_connect("localhost","username","password","dbase");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT * FROM Hits WHERE timestamp BETWEEN '$startdate' AND '$enddate'";
if ($result = mysqli_query($con,$sql)) {
$visitors = mysqli_num_rows($result);
}
$sql="SELECT DISTINCT session FROM Hits WHERE timestamp BETWEEN '$startdate' AND '$enddate'";
if ($result = mysqli_query($con,$sql)) {
$sessions = mysqli_num_rows($result);
}
$sql="SELECT DISTINCT country FROM Hits WHERE timestamp BETWEEN '$startdate' AND '$enddate'";
if ($result = mysqli_query($con,$sql)) {
$countries = mysqli_num_rows($result);
}
$sql="SELECT DISTINCT city FROM Hits WHERE timestamp BETWEEN '$startdate' AND '$enddate'";
if ($result = mysqli_query($con,$sql)) {
$cities = mysqli_num_rows($result);
}
$output = json_encode(array("visitors"=>$visitors,"sessions"=>$sessions,"countries"=>$countries,"cities"=>$cities,"startdate"=>$startdate,"enddate"=>$enddate));
echo $output;
mysqli_free_result($result);
mysqli_close($con);
However the dates returned by PHP are 18 hours behind the dates which JS passed to PHP - very weird! My browser and MAMP server are on the same machine (my iMac) and I live in Thailand (UTC + 7 hours).
Here's a screen shot of what is displayed in HTML using the following code:
<div id="reportTitle">
Report of site activity from
<span id="startTime"></span>on<span id="startDate"></span>to
<span id="endTime"></span>on<span id="endDate"></span><br>
for<span id="showVisitors"></span>
<span id="showCities"></span>
<span id="showCountries"></span>
</div>
<div id="reportBody">
<div>
<span><h3>From</h3></span><span id="PHPStartDate"></span>
<span><h3>to</h3></span><span id="PHPEndDate"></span>
The first set of dates displayed at the top of the screenshot are simply the JS startdate and enddatevariables and the lower set of dates are those returned by the PHP variables $startdate and $enddate which ought not to have changed (but in fact are 18 hours earlier!).
Screenshot of JS and PHP dates
I suspect the problem is to do with timezones but given that Thailand is UTC+7 it's hard to work out where the 18 hour time difference is coming from.