I have a database which id,title,subject and datetime and I'm calling a php page that takes in a request from clients to show the latest entry in the db from the difference of time from the client and checks with the last entry's datetime. PHP code as follows
$date = "2012-10-06 18:13:52";
//Establish a connection
$conn = mysql_connect('localhost','regadmin','regadmin');
//Select the mySQL db
$db = mysql_select_db('easy_comm', $conn);
$sql = mysql_query("SELECT `title`, `subject`,`date_sent` FROM `books` WHERE `date_sent` > '$date'", $conn);
$count=mysql_num_rows($sql);
if($count != 0){
$json = array('boolean' => true);
}
else{
$json = array('boolean' => false);
//echo "No record";
}
From the above code and the provided $date variable, it will always return true and the last entry is
2012-10-06 18:10:52
I have tried converting to UNIXTIMESTAMP but same problem
Well this works good enough for me.Please make sure the column against which you are comparing the date surely happens to be DATETIME column not a VARCHAR or something else.
Please post us database structure to see the collation as well and also try printing the query on the fly and then execute in your console.
Related
I want to send a reminder to my subscribers a month before their subscription ends, i have columns validity and reminder (type VARCHAR) in my MYSQL DB
date stored in those columns are saved using php date function
$validity = date('d/m/Y',strtotime("6 months"));
$reminder = date('d/m/Y',strtotime("5 months"));
now i want to send a mail when the current date is equals reminder date
I have a test entry with reminder value 22/06/2017 and $date variable echo the same value.
$date = date('d/m/Y');
$q = 'SELECT * FROM subscriptions WHERE reminder = "$date"';
$r = mysql_query($q);
if(!$r){
echo 'query err';
}
$a = mysql_num_rows($r);
echo 'No of rows returned '.$a;
*mailing script after this line*
this script outputs No of rows returned 0
Can someone give me some idea how i should approach this
First i suggest you your date format is change in database and type change datetime.
This format follow for you insert reminder date
$reminderdate = date('Y-m-d');
Then compare with currentdate when fetch data from database:
$date=date('Y-m-d');
if($r['reminder']==$date)
{
echo 'Mail sent here';
}
else
{
echo 'date not match';
}
Your script is at risk for SQL Injection Attacks, see this
The issue is here:
'SELECT * FROM subscriptions WHERE reminder = "$date"';
change it to:
"SELECT * FROM subscriptions WHERE reminder = '".$date."'";
to compare date, you have to wrap it into single quotes '
A few suggestions:
the reminder column may be redundant depending on your logic
in the future please use different approach to connect to the database, for example: http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
the validity column should rather be DATETIME format
Now to your main question - it can be because of datetype mismatch so switch in database to DATETIME and in PHP use date('Y-m-d').
First Of all You should not store date in varachar.
Now to compare dates in varchar first you have to convert the string(varchar) into date.
for that you can use mysql's function:
str_to_date
You can get the example how to convert it and then compare it to get the result.
$q = "SELECT * FROM subscriptions WHERE reminder = '{$date}'";
I Know You have selected the answer already and ignored the comments, because you just want to get this done with and move on no matter how you did it. I will just make this answer a community WIKI.
Below are the things you need to note :
The API that you are using have depreciated for a long time ago rather use mysqli or even better PDO with prepared statements.
Also What I'm sure when the use subscrips on your website, you should have a column that stores the duration of the subscription and the actual expire date and a flag to identify expired subscriptions.
Mysql does provide its own date time functions, which you can use and use the date type on these columns.
Use API that is still active and maintained that is mysqli_* or pdo they both support prepared statements.
$host = '127.0.0.1';
$db = 'DBNAME';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
);
$dbh = new PDO($dsn, $user, $pass, $opt);
$stmt = $dbh->query("SELECT * FROM subscriptions WHERE subscriptionsExpireColumn = DATE_ADD(CURDATE(), INTERVAL 1 MONTH)");
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
} else {
$results = $stmt->fetchall();
if (count($results) > 0) {
foreach ($results as $row) {
//DO WHAT EVER YOU WANT TO DO WITH THE RESULTS
}
} else {
echo "no records found";
}
}
?>
Hi i was using this code in the last months but suddenly it stop working and it doesn't store the data in the database, it's config with the auto increment value and it just stopped in the "87" after that i can't make it to work
<?php
$connect = mysql_connect("host","user","pass");//database connection
if($connect){
echo("+");
}else{
echo("-");
}
$make = mysql_select_db("database");
if($make){
echo("+");
}else{
echo("-");
}
// Get values from form
$renovarum=$_POST['repnovarum'];
$cargorepnov=$_POST['cargorepnov'];
$razonsocial=$_POST['razonsocial'];
$rfcli=$_POST['rfcli'];
$representante=$_POST['representante'];
$cargorepcli=$_POST['cargorepcli'];
$nombrecomercial=$_POST['nombrecomercial'];
$calleynum=$_POST['calleynum'];
$calle3=$_POST['calle3'];
$calle5=$_POST['calle5'];
$calle6=$_POST['calle6'];
$calle4=$_POST['calle4'];
$personafm=$_POST['personafm'];
$escritura=$_POST['escritura'];
$fechaescr=$_POST['fechaescr'];
$abogado=$_POST['abogado'];
$numnotario=$_POST['numnotario'];
$ciudades=$_POST['ciudades'];
$numcomer=$_POST['numcomer'];
$fechapro=$_POST['fechapro'];
$emailcont=$_POST['emailcont'];
$liderproyecto=$_POST['liderproyecto'];
$fechainicio=$_POST['fechainicio'];
$fechavencimiento=$_POST['fechavencimiento'];
$entregables=$_POST['entregables'];
$inforeq=$_POST['inforeq'];
$pago=$_POST['pago'];
$pago2=$_POST['pago2'];
$formadepago=$_POST['formadepago'];
$diaspago=$_POST['diaspago'];
$fecprimerpago=$_POST['fecprimerpago'];
$telefono=$_POST['telefono'];
//inserting data order
$order = "INSERT INTO contratos_finales2
(repnovarum,cargorepnov,razonsocial,rfc,representante,cargorepresentante,nombrecomercial,calleynum,colonia, ciudad,estado,cp,tiporeg,numescritura,fechaescritura,nombrenotabo,numnotpub,ciudadescr,numpropycom,fechaproycom, emailcont,liderproy,fechaini,fechafin,entregables,inforeq,cantnum,canletra,formadepago,diadepago,fechaprimerpago,telefono)
VALUES
('$renovarum','$cargorepnov','$razonsocial','$rfcli','$representante','$cargorepcli','$nombrecomercial','$calleynum','$calle3','$calle5','$calle6','$calle4','$personafm','$escritura','$fechaescr','$abogado','$numnotario', '$ciudades','$numcomer','$fechapro','$emailcont','$liderproyecto','$fechainicio','$fechavencimiento','$entregables','$inforeq','$pago','$pago2','$formadepago','$diaspago','$fecprimerpago','$telefono')";
//declare in the order variable
$result = mysql_query($order); //order executes
if($result)
{
echo("
+");
}
else
{
echo("
-");
}
?>
i need to keep saving the data in the form but i can't make it work i don't know if i have to make a change i didn't change anything in the database it's te same version and connection from the beginning.
Please check the data type of your auto increment field, it may possible that your data type is tiny int or have less length. You need to change your datatype to INT and length as 11 or as per your requirement.
Your code is vulnerable to sql injection. Who knows what one did to your database. At least do a minimum sanitization with mysql_real_escape_string();
Can you add data to your table from phpmyadmin via UI? Any error messages? Try to run your query in phpmyadmin's cmd tool.
please correct this
$make = mysql_select_db("database");
$connect = mysql_connect("hostname","username","password");//database connection
$make = mysql_select_db("database",$connect);
bool mysql_select_db ( string $database_name [, resource $link_identifier = NULL ] )
please take a look here
I am new to php as well as SQL Server, so if my question is too trivial please bear with me. Our company just migrated database from MySQL to SQL Server 2008. I am having problem retrieving datetime properly from the database. The field in question is of datetime type. The code i use is -
$query = "select name,rdatetime from names order by name";
$result = mssql_query($query);
while($row=mssql_fetch_array($result))
{
$name = $row["name"];
$rdatetime = date('Y-m-d H:i:s',strtotime($row["rdatetime"]));
}
When I print this $rdatetime it shows as 2014-03-07 16:17:00. The ss part is always 00, even when there are other values in the database. I even tried the DateTime object
$rdatetime = new DateTime($row["rdatetime"]);
echo $rdatetime->format("Y-m-d H:i:s");
But the results are same. Can anyone tell me what can be the problem ?
I need to create a script that compares one field in the database (has a date stored, it's type is "TEXT" and cannot be changed DATE) to the current server date.
The dates are encoded like this "1380571547", so i need to use strftime() to decode them. This field for example, decoded with strftime corresponds to this "Sep-30-2013, 22:05"
What I need is to compare those fields with the current date, and according to that condition, write something like "Expired" in another field.
To achieve this, I made this block of code:
<?php
require("connection.php");
$today = strftime('%b-%d-%Y, %H:%M');
$exp_date = mysql_query("SELECT numbers FROM date");
while($row = mysql_fetch_array($exp_date))
{
echo (strftime ( '%b-%d-%Y, %H:%M', $row ['numbers'])). "<br />";
}
if ($exp_date < $today) {
$sql = "INSERT INTO date (changed) VALUES ('EXPIRED')";
$result = mysql_query($sql);
echo "ADDED!";
}
?>
However, this code is not working, can someone help me ?
PHP is not my strong point but it looks to me like you condition is doing a comparison on an array,
IE:
if ($exp_date < $today) // will always be false.
Your code would probably have to look something more like this.
while($row = mysql_fetch_array($exp_date))
{
if ($row[0] < $today)
{
$sql = "Update date set changed = VALUE where rowid = rowid";
$result = mysql_query($sql);
echo "ADDED!";
}
}
having said that i would probably do the comparison and update in SQL using a case statement,
Update Date
set changed = case when number > ExpiryDate
then "Expired"
else "Current"
end
You can do all this in a single query:
UPDATE `date` set `changed`='Expired' where date(now()) > date(from_unixtime(`numbers`))
But this is not what your code is attempting to do. Your second block seems to be inserting the word Expired in new rows, rather than updating anything.
Note that the table name date should be wrapped in backticks to avoid any possible clash with MySQL keywords
I don't understand the second block of code with the insert. I would do an update inside the loop. but if your going to do that, it could probably be done in one combined update statement.
I am trying to list out all records from a database that have not expired.
i have a jobs listing site being developed, i have code to grab all the 'active' job details from the database and list out.
$mysql = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('There was a problem connecting to the database');
$stmtJ = $mysql->prepare('SELECT id,jobtitle,vcref,jobtype,jobintro,closingdate FROM jobs WHERE active = 1');
$stmtJ->execute();
$stmtJ->store_result();
$stmtJ->bind_result($id,$jobtitle,$vcref,$jobtype,$jobintro,$closingdate);
$totalLiveJobs = $stmtJ->num_rows();
and is outputted like so:
<?php
while($row = $stmtJ->fetch()) :
echo("<p>job detail here</p>");
endwhile;
?>
and i also have an 'if statement' snippet to see if the job has expired or not (i.e if expires {expires is a date yyyy-mm-dd} is greater than '$now' it should not show up.
$expires = date('Y-m-d-H-i-s',strtotime("$closingdate 12:00:00"));
$now = date('Y-m-d-H-i-s');
if ($expires < $now) {
echo ("<h3>Live Jobs Here</h3> $expires");
} else {
echo ("<h3>Job Expired</h3> $now");
}
However, i'm having problems merging the two together with the main goal being all jobs that have not yet expired will be shown on the page, any jobs that have expired should not be shown on the page.
I am pulling my hair out here, any help welcome, any requests for further details i'll respond as soon as i possibly can.
thx in advance
depending on your database structure, you could do
SELECT * FROM jobs WHERE active = 1 AND closingdate >= NOW()
You can merge two SQL query results together that have the same returned columns using UNION.
See more here: W3C Schools: SQL Union.
If all data stored within one table you can use this query:
SELECT id,jobtitle,vcref,jobtype,jobintro,closingdate
FROM jobs
WHERE CONCAT(closingdate, ' 12:00:00') > '{$mysql_timestamp}' AND active = 1
Note: mysql timestamp format is
date('Y-m-d H-i-s')
also you can use built in NOW() function, however depending on your hosting location there might be different timezone from your website audience.