On my website I am attempting to make a countdown timer. The same code for the timer works if I tell it the value of the column and it works on a test php page. The problem is that the mktime value is not being read right from the mysql database. However if I put the column to output inside of an echo it outputs fine. The column that contains the data is called expire. The other values I am loading from mysql are inside of he echo however all connection statements are made before I call any. I am using the mysqli_fetch_array to call the values.
$target = mktime($row['expire']);
$today = time();
$difference = $target-$today;
$hours = $difference/3600;
$minutes = ($hours-floor($hours))*60;
echo('ENDS IN: '.floor($hours).' Hrs '.floor($minutes).' Mins');
Yes the document is HTML that it gets included into
The way I formatted the expire column in mysql was standard as Hr,Min,Sec,MM,DD,YYYY. The actual content of the column is "21,0,0,7,12,2017"
Thanks in advance, David.
The problem is, that you get a string from your database in $row['expire']. But mktime() is an integer only function. So, first you need a workaround to explode and convert your string to integers, before it will work with mktime().
Please delete the following line from your code:
$target = mktime($row['expire']);
Try this instead:
$timeparts = array_map('intval', explode(',', $row['expire']));
$target = mktime($timeparts[0],$timeparts[1],$timeparts[2],$timeparts[3],$timeparts[4],$timeparts[5]);
Hope it was helpful. But please do not save timevalues as a string in your database. Read about other possibilities in the manual.
Related
Trying to make a little Search feature for a user, so he can type in a date on a webpage made with HTML/PHP, and see which people in the db have registered as member on or after (a date). My user inputs the date in format 2015-10-01. This gets sent to a PHP page with a jqxGrid on it, populated with member details of members conforming to my query on the MySQL database (using PDO).
The query uses the operator >= on a string passed as (for example) "2015-10-01" in the WHERE clause, so I am using STR_TO_DATE to make the comparison work:
WHERE `lastUpdated` >= STR_TO_DATE( ? , '%Y-%m-%d');
With PDO, the ? later gets bound to the date (which was passed in as a string).
The db column for registration date is in DATETIME format, and in the db values look like: "2015-10-12 17:12:52".
My query returns an empty array every time, - and this after many hours of trying every conceivable permutation of date format, both in the MySQL statement and on the page that prepares the data for populating the grid.
Can someone show me what's wrong here?
Thanks!!
SP
Make it
WHERE `lastUpdated` > ?
and check your data and stuff.
Basically, you should never touch PDO until you get raw SQL to work.
okay, so here is the PDO version that works - passing in ? instead of the date:
function getJSONAllMembersByDate($PDOdbObject, $regDate)
{
try
{
$membersByDateSQL = "SELECT `id`, `name_first`, `name_last`, `organization`,`email`, `phone`,`source`,`comments`,`language_id`, `lastUpdated` FROM `member` WHERE lastUpdated>=?";//'$regDate'
$get=$PDOdbObject->prepare($membersByDateSQL);
$get->execute(array($regDate));
$rows = $get->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($rows);
return $json;
}
The fact that it works proves there were other errors in the file containing the jqxwidget (the version before I posted here). I certainly tried about a million different things to get this working.
I don't know if this counts as an answer, but at least it WORKS! There are so many variables in this problem - json, jqxgrid, pdo ... not forgetting that there are several ways to use PDO. I probably had several errors in different places.
(#apokryfos, the STR_TO_DATE was indeed unnecessary.)
In the end, this is what works:
In the PHP page containing the jqxGrid, the url sent to the server is:
url: 'my-json-responses.php?fct=getJSONAllMembersByDate®Date=<?php echo $fromDate ?>'
This $fromDate comes from the $_POST when the user typed in a date (in the format 2015-10-01) on the input page. When the PHP page containing the jqxGrid loads, it does
$fromDate = $_POST['regDate'];
The url "transits" through the file my-json-reponses.php, which contains many functions. It finds the right one:
if ($_GET['fct'] == 'getJSONAllMembersByDate')
{
$result = getJSONAllMembersByDate($connectionObject, $_GET['regDate']);
echo $result;
}
The $result is called on the file that contains all my PDO database requests, including:
function getJSONAllMembersByDate($PDOdbObject, $regDate) { try
{
$membersByDateSQL = "SELECT `id`, `name_first`, `name_last`, `organization`,`email`, `phone`,`source`,`comments`,`language_id`, `lastUpdated` FROM `member` WHERE lastUpdated>='$regDate'";
$get=$PDOdbObject->query($membersByDateSQL);
$rows = $get->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($rows);
return $json;
}
catch (PDOException $e)
{
echo "There was a problem getting all members with this search query.";
echo $e->getMessage();
}}
Note that I couldn't make the version using "?" in the query work at all, hence passing in the variable $regDate directly, with single quotes around the variable just to make life interesting.
This returns a nice list of all my users as of 2015-10-01 - but is presumably still open to MySQL injection attacks ...
But after this marathon of debugging I am happy enough for now. (All improvements welcomed, naturally!)
SP
can anyone help me with this:
$querydate ="SELECT DATE_FORMAT(NOW(),'%m-%d-%Y') AS dat";
$query = mysql_query($querydate);
$row = mysql_fetch_assoc($query);
$fecha = $row['dat'];
-2013-31+07 it is returning -2037
And i want it to return today's date
31-07-2013
Try this
SELECT DATE_FORMAT(NOW(),'%d-%m-%Y') AS dat
Here you have more info for the format of date
Given your code example, a value of '07-31-2013' should be assigned to fecha;
If you want the day before the month, then change the format string to '%d-%m-%Y'.
Evaluated in a numeric context, the expression -2013-31+07 should return -2037. That is expected behavior.
But we don't see in your code where this evaluation is taking place.
There could be reasons for pulling the date that aren't apparent in your question, but if your MySQL implementation is on the same machine as your php code then you could get the results your looking for by running:
$fecha = date("d-m-Y");
And save yourself the database call.
I asked a question about bigints yesterday which was kindly answered. However, I have been observing some weird behaviour and would like to understand what is going on.
In my php I have an array which I send back to a javascript web client program which uses it.
In the php
sendBack = null;
sendBack[0]['TimeStamp'] = $Time; // A bigint got from a mysql table milliseconds from 1970
sendBack[0]['Text'] = $Message; // A varchar message got back from mysql
// I am guessing at this point you have worked out this is a text-chatroom thing going on
sendBack[1]['TimeStamp'] = 0; // A zero indicates an admin issue - note its an int but a small one
sendBack[1]['Text'] = $MessageAdmin;
// And I pack it up to send back
echo json_encode($sendBack);
In the js I unpack it to use with:
var json = eval('(' + data + ')');
The problem is, the 0 index TimeStamp in the js is being treated as a string but the index 1 Timestamp is being treated as an int.
From an educational point of view does anyone know what is going on?
I believe values returned from a database with PHP are always strings. In order to convert your zero-index timestamp you'd need to do something like:
sendBack[0]['TimeStamp'] = parseInt($Time, 10);
which will convert it to an integer value (base-10).
Obviously the 1-index timestamp is being set as zero directly hence the reason it's returning as an int.
I have added time stamp and date when the details should create. and the time stamp and date will add in database. When i'll retrieve it from db it wanna to show only that string name without time stamp and date ? how to make it?
Adding Method....
$imagename = $_POST['imagename'];
$imageNameExt = $_POST['imageNameExt'];
$newImgName = trim($imagename).'_'.date('Y_m_d_H_i_s').'.'.trim(strtolower($imageNameExt));
Here consider the $imagename = "abc"; and $imageNameExt = "jpg"; when it'll insert into db the name as $newImgName = "abc_2011_07_12_18_47_02.jpg"....
Now i need to retrieve from db..How should i print only the name "abc" with out the time stamp and date??
Thanks in advance.
Update : (I couldn't post this as a answer bcoz am under 100 reputation.)
found the answer for my question:
While am retrieving it'll come in the name of image_path,
$image_path = $rows[0];
$tmp = "_".date('Y');
$ImgOrgName = explode($tmp,$image_path);
$ImgOrgName_core = $ImgOrgName[0];
The Image name "abc" will come in the string "$ImgOrgName_core".
Try it...i'm easily getting the answer when i use like this.
You should store the original image name and the timestamp information as separate columns in the database. This way you will always have access to each piece of data, and you can concatenate them as you currently do before inserting any time you wish.
You can also hammer your existing code into submission by simply getting the string and counting underscores from the end until you find the 6th (there are 5 in the timestamp so the 6th from the end separates the timestamp from the name), or you can simply remove the last 20 characters from the name with substr (the timestamp is 19 chars if all numbers are padded with zeroes, plus 1 char for the separator underscore), but this kind of solution is messy and prone to breakage. I would never recommend it, so I don't give code for it (and anyway, cutting off the last 20 characters is trivial).
You cat replace date with regexp:
$imgNameNoDate = preg_replace('#_\d{4}_\d{2}_\d{2}_\d{2}_\d{2}_\d{2}#', '', $imgName);
But better way is to change your database to store original name and datetime information.
While I agree with the commenters that it would be much, much better to store the timestamp in its own column, here's how to do specifically what you want.
$underscorePos = strpos($imageNameFromDB, '_');
if ($underscorePos !== false)
{
$imageNameOnly = substr($imageNameFromDB, 0, $underscorePos);
}
found the answer for my question:
While am retrieving it'll come in the name of image_path,
$image_path = $rows[0];
$tmp = "_".date('Y');
$ImgOrgName = explode($tmp,$image_path);
$ImgOrgName_core = $ImgOrgName[0];
The Image name "abc" will come in the string "$ImgOrgName_core".
Check it...i'm easily getting the answer when i use like this.
I am attempting to grab a date supplied via POST, then generate a list of dates over a 12 week period from the supplied start date. These dates would then go into the DB and a 12 week schedule would be output, which the user can interact with (add/edit/delete).
I am successfully taking the start date, generating the 12 week date list and adding this into the DB in serialized form, but when it comes to selecting the dates for display, I get the following error:
Notice: unserialize() [function.unserialize]: Error at offset 0 of xxx bytes in ...
Here is my code:
1st .php file here to take a form input (a date) and then get a list of each date over a 12 week period from the start date, and insert into the DB:
The array:
$start = strtotime($_POST['Start_Date']);
$dates=array();
for($i = 0; $i<=84; $i++)
{
array_push($dates,date('Y-m-d', strtotime("+$i day", $start)));
}
$savetodb = serialize($dates);
The insert:
$sql = "INSERT INTO programme VALUES (NULL, '20', '".$_POST["Start_Date"]."' , ' ".$savetodb." ', '".$_POST["Programme_Notes"]."')";
2nd .php file here - SELECT and unserialize:
$result = mysql_query("SELECT Programme_Dates FROM programme");
while($row = mysql_fetch_array($result))
{
$dates = unserialize($row["Programme_Dates"]);
echo $dates;
}
From what I've read the problem could be related to the DB column where the serialized array is inserted (ie being too small), but it is set to TEXT so that should be fine right? I also thought there may be certain characters within a date causing problems, but when testing with a "regular" array (ie just text), I get the same errors.
Any suggestions / hints much appreciated, thanks.
Why are you using stripslashes? My bet is that is the problem. Remove that from there and see if it works.
As a side note, stripslashes should be avoided as if data is probably inserted into the database they should be escaped properly meaning no extra slashes should be added. If you need to stripslashes from the data itself I would suggest using something like array_filter after you unserialized the array.
EDIT
You should also look into SQL Injection and how to prevent it, as your code is suseptible to be exploited.
UPDATE
Looking further at your code you insert the serialized array with 2 extra spaces: ' ".$savetodb." ', try using just '".$savetodb."', that and see if it fixes your issue.
i have found that the serialize value stored to database is converted to some other way format. Since the serialize data store quotes marks, semicolon, culry bracket, the mysql need to be save on its own, So it automatically putting "backslash()" that comes from gpc_magic_quotes (CMIIW). So if you store a serialize data and you wanted to used it, in the interface you should used html_entity_decode() to make sure you have the actual format read by PHP.
here was my sample:
$ser = $data->serialization; // assume it is the serialization data from database
$arr_ser = unserialize(html_entity_decode($ser));
nb : i've try it and it works and be sure avoid this type to be stored in tables (to risky). this way can solve the json format stored in table too.