Submit timestamp to mysql - php

I am trying to add a timestamp to my database when I update a form, and for reason that I do not know, I am getting an error... and when just trying to insert the year, month, day I get "1988" inserted into my database. I use a similar timestamp elsewhere on the same site and it works fine. What am I doing wrong?
Note: yes I know I should be using mysqli and I'm vulnerable to sql injection. I plan on converting the entire site later in the year.
$homeScore = ((strlen($game['homeScore']) > 0) ? $game['homeScore'] : 'NULL');
$homeOdds = (str_replace("\xBD", ".5", $homeScore));
$visitorScore = ((strlen($game['visitorScore']) > 0) ? $game['visitorScore'] : 'NULL');
$visitorOdds = (str_replace("\xBD", ".5", $visitorScore));
$odds_timestamp = date("Y-m-d g:i:s A");
$sql = "update " . $db_prefix . "schedule ";
$sql .= " set odds_timestamp = " . $odds_timestamp . ", homeOdds = " . $homeOdds . ", visitorOdds = " . $visitorOdds . "";
$sql .= " where gameID = " . $game['gameID'];
mysql_query($sql) or die('Error updating odds: ' . mysql_error());

You have missing (single) quotes " . $odds_timestamp . "
that will need to be '" . $odds_timestamp . "' since it will contain characters that MySQL will complain about... being hyphens.
That is a string.
Now, if any of your other variables are also strings, they too need to be quoted as shown.
I.e.: '" . $string . "' as opposed to " . $integer . "
More on string literals:
https://dev.mysql.com/doc/refman/5.0/en/string-literals.html
Pay attention to Riggs' comments, one of which being:
"You would be best advised to make the datatype a DATETIME or TIMESTAMP as if you keep the VARCHAR it will make the data much more difficult to process later. Just change the date() to produce a legal MYSQL data format"
Using a VARCHAR won't fix it, as it still considered as a string literal for the column.
New comments by Riggs:
"You would be best advised to make the datatype a DATETIME or TIMESTAMP as if you keep the VARCHAR it will make the data much more difficult to process later. Just change the date() to produce a legal MYSQL data format. You can always add the AM/PM when you present the date time to any user. VARCHAR date/time will really mess with your selection criteria later as well. Remember - Database for DATA, Browser for PRESENTATION"

You can use MySQL's NOW() function, which returns current datetime.

Without error message, Its difficult to say something.
or if you can print your query it will be helpful.
but try with.
odds_timestamp = '" . $odds_timestamp . "'
to make it explicit string.

Try adding a timestamp column in the database table with an on update set current timestamp clause.
Heres a simple example from MySQL Documentation:
CREATE TABLE t1 (
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
Should take care of it and cut out the middle man. Win-win.

Related

Find a random time with an integer

I am looking to generate a random number say 01:20 and then add 8 hours onto that and store that as a variable. However I want to do this within only the time and not use any random integers.
The date given for the query is found using a preset date at the moment set to 01-01-2017. StaffID is gotten from a loop through another table.
This is the PHP code snippet.
strtotime($random_hour = rand(00,23));
echo $random_hour . " Hour <br> ";
strtotime($random_min = rand(01,59));
echo $random_min . " Min <br> ";
$randomhourmin = $random_hour . ":" . $random_min;
echo $randomhourmin . "<br>";
This is the final SQL insert query.
$sql = "INSERT INTO schedule (staffID, cdate, starttime, endtime, dayoff) VALUES ('$rowID','$fDate','$randomhourmin','$randomhourmin','0')";
You can use below
$int= rand(1262055681,1262055681);
Also check mt_rand(), which is to have better randomness in the results:
$int= mt_rand(1262055681,1262055681);
To turn a timestamp into a string, you can use date(), ie:
$string = date("Y-m-d H:i:s",$int);

What's wrong with this php code? im trying to concatenate

$result = mysql_query("SELECT * FROM `deceased` WHERE `birthdate` = '{$birthmonth}'. "-" .'{$birthday}'. "-" .'{$birthyear}'");
You shoudn't use dots into the string.
But much better way is avoid to inject variables into the strings and use explicit concats:
$result = mysql_query("SELECT * FROM `deceased` WHERE `birthdate` = '" . $birthmonth . "-" . $birthday . "-" . $birthyear . "'");
Try to concatenate your variables inside your quotes as follow
$result = mysql_query("SELECT * FROM `deceased` WHERE `birthdate` = '".$birthmonth . "-" . $birthday . "-" . $birthyear."');
As side note i would advise you to switch to either PDO or mysqli since mysql_* api are deprecated and soon will be no longer mantained
From the MYSQL documentation on the Date type:
The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.
So there is a good chance that your query is not getting you what you want since you are searching based on an incorrectly formatted date. What you want, instead, along with correctly formatted PHP, is:
$result = mysql_query("SELECT * FROM `deceased` WHERE `birthdate` = '$birthyear-$birthmonth-$birthday'");

Cannot send a database timestamp through JavaScript but can send other values

I'm using PHP5, MySQL, JavaScript and Fusion Charts.
I have the following time value returned from a database: 2011-12-19 12:00:00
After taking it from the database, I try to pass it through a JavaScript strURL to get it to another page where I can make further database calls using this value. The problem I have is that the JavaScript fails whenever I send it through a date/time. I can send through any other value type and it works so the problem seems to be with the time stamp. I've tried converting it to string before it is passed (just to be sure it's not one already) and that doesn't work. I'm guessing it's to do with the characters within the value. Any idea how to get around this?
The database call in PHP and then sending fields into the JavaScript:
$strQuery = "SELECT unit, watts, time, device, siteid FROM inverter WHERE time = '2011-12-19 12:00:00' AND siteid = '842'";
$result2 = mysql_query($strQuery) or die(mysql_error());
if ($result2) {
while($ors2 = mysql_fetch_array($result2)) {
$thetime = (string)$ors2['time'];
$strXML .= "<set color='58ACFA' label='" . $ors2['device'] . "/" . $ors2['unit'] . "' value='" . $ors2['watts'] . "' link='javaScript:updateChart(" . $ors2['unit'] . " , " . $ors2['device'] . " , " . $ors2['siteid'] . " , " . $thetime . ")'/>";
}
}
And then the JavaScript function:
function updateChart(first, second, third){
//DataURL for the chart
var strURL = "FactoryData.php?factoryId=" + first + "&device=" + second + "&siteid=" + third;
FusionCharts("FactoryDetailed").setXMLUrl(strURL);
}
link='javaScript:updateChart(" . $ors2['unit'] . " , " . $ors2['device'] . " , " . $ors2['siteid'] . " , " . $thetime . ")'
This JavaScript becomes something like
updateChart(341, 454, 842, 2011-12-19 12:00:00);
The first three arguments are valid numbers (I assume the IDs are integers), but the fourth argument causes a syntax error. What you need to do is wrap it in quotes to make it a string:
link='javaScript:updateChart(... " , \"" . $thetime . "\")'
^^ ^^
Now the JavaScript should be like this:
updateChart(341, 454, 842, "2011-12-19 12:00:00");
You can either convert the date to a timestamp with something like
new Date('2011-12-19 12:00:00').getTime()
or encode it using encodeURIComponent('2011-12-19 12:00:00')
The latter is probably the better solution, as it works with all kinds of values, not only dates. You can use decodeURIComponent if you want to read the parameters on the client side, that should already be working fine on the server side.

PHP - error when insert date into MySQL

I've got a typical problem when trying to insert a date into MySQL.
The column defined in MySQL is of type DATE. My PHP version is 5.3.0
Apart from this date-related issue, the rest of my code works just fine.
And this is my PHP script to do this:
$tablename = BOOKS_TABLE;
$insert = mysql_query("INSERT INTO $tablename (barcode, book_name, volume_num,".
" author, publisher, item_type, buy_price, buy_date) VALUES ".
"(".
"'" . $barcode . "', ".
"'" . $bookname . "', ".
"'" . $volumenum . "', ".
"'" . $author . "', ".
"'" . $publisher . "', ".
"'" . $itemtype . "', ".
"'" . $buyprice . "', ".
"'" . getMySQLDateString($buydate). "'".
//"'STR_TO_DATE('".$buydate ."', '%d/%m/%Y'))'". //nothing changes in MySQL
")");
And this is the faulty function :
function getMySQLDateString($buydate) //typical buydate : 04/21/2009
{
$mysqlDateString = date('Y-m-d H:i:s', $strtotime($buydate));
return $mysqlDateString;
}
The first commented out line wouldn't do anything, the script is executed with no error, however, there is nothing changed in datebase after this.
The current approach will cause a Fatal error saying function name must be a string in this line.
Actually I followed this thread on SO, but just cannot pass the date into MySQL...
Can anyone help me figure out which part is not right?
How would you do it, in this case, to get it right?
Sorry about such a journeyman-like question, thanks a lot in advance.
Updated:
Thanks for reminding me this, and here is the exact error message as the html output :
Fatal error: Function name must be a string in C:\xampp\htdocs\comic\app\insertBookIntoDB.php on line 85
which point to the line starts with
$mysqlDateString = date('Y-m-d H:i:s', $strtotime($buydate));
In the following line:
$mysqlDateString = date('Y-m-d H:i:s', $strtotime($buydate));
Should this be:
$mysqlDateString = date('Y-m-d H:i:s', strtotime($buydate));
(eg. remove the dollar on the function) ?
Not sure if that the cause of your problem, but you seem to be missing the closing here :
"'" . getMySQLDateString($buydate).
should be
"'" . getMySQLDateString($buydate)."'"
This must be a comment but in sake of code formatting.
Despite of the fancy formatting, your code helps you nothing is such a case.
To make it much more useful, you have to add some debugging features in it.
Sensible variable names also helps
As well as removing function call from the string building
$sqldate = getMySQLDateString($buydate);
$sqldate = mysql_real_escape_string($sqldate);
//we name this variable $sql because it contains an SQL query
$sql = "INSERT INTO $tablename (barcode, book_name, volume_num,
author, publisher, item_type, buy_price, buy_date) VALUES
(
'$barcode',
'$bookname',
'$volumenum',
'$author',
'$publisher',
'$itemtype',
'$buyprice',
'$sqldate'
)";
//we name this variable $res because it's a resource
//type variable contains query result
$res = mysql_query($sql) or trigger_error(mysql_error().htmlspecialchars($sql));
upon execution, this code will tell you comprehensive information on the error, if any occurred.
In my opinion, storing dates using explicit date formats is annoying, and all the string conversion irritates me. I'd recommend using a BIGINT for the date field, and storing an epoch time value in the database.
You can get epoch time with PHP:
time();
Or, with more precision:
microtime();
Plus, you can manipulate them easily. To change the date to next day:
$myTime + 86400;
This epoch time format is very easy to store and use and isn't bugged with all the string conversion nonsense. To get a neat string from the value:
date("FORMAT STRING", $myTime);

loop through mysql database records and change phone formats

I'm working on a legacy database table that has a phone no. field
but the problem is that all the entries (over 4k) are in varying
formats.
I was wondering if there was a quick way to fix them by looping through the records using PHP and updating the records to a particular phone format
4K doesn't sound like many records at all.
And I'd bet that the varying formats fall into a finite number of combinations.
I wonder if it'd be possible with a few judicious SQL queries. If your RDBMS has regular expressions and string replacement functions you could manage it with a few UPDATE instructions. If not, any language with the capability of querying a database, doing string replacement, and updating would do the job.
I agree 4k records isn't anything to worry about. I suggest querying the phone numbers and the primary id of the table, stripping all characters from phone number and then manipulating it to be the format you want. Or, you could keep it as only numbers and use your front-end to modify the number every time you display it. Below is a little untested script you can try to use. Doesn't handle extensions and expects there are 10 numbers.
// mysql_connect stuff
$q = mysql_query("Select phone_id, phone_number From phones");
while($r = mysql_fetch_assoc($q)) {
$num = ereg_replace("[^0-9]", "", $r['phone_number']);
if(strlen($num) == 10) {
$num = substr($num, 0, 3) . '-' . substr($num, 3, 3) . '-' . $substr($num,-4);
}
$update = mysql_query("Update phones Set phone_number = '" . $num . "' Where phone_id = " . $r['phone_id']);
// updated?
}

Categories