I'm gathering some info from a website to put it in a MySQLdatabase. At this moment I just cannot find out how to get the date and time in the database.
I tried several things, can you help?
$write="REPLACE INTO `".$database."`.`db` (`1`,`2`,`3`,`4`,`5`,`6`,`7`,`datetime`) VALUES ('".$1."','".$2."','".$3."','".$4."','".$5."','".$6."','".$7."','**SO WHAT DO I NEED TO PLACE HERE**')";
echo $write;
$query = mysql_query($write) or die (mysql_error());
In the database itself no matter what I put in my php, is 0000-00-00 00:00:00.
just passed value NOW(), example
INSERT INTO tb(col1) VALUES(NOW())
As a sidenote, the query is vulnerable with SQL Injection if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.
How to prevent SQL injection in PHP?
if it's fine to use server's current date/time then use NOW() function
Related
I have a small problem. I'm using PHP with Oracle (new to the Oracle by the way).
In my database there's a DATE field called NEXT_START_DATE and it's value is
25.12.2013 04:05:01
as you can see below.
The thing is I can get date values just fine in my web page, but couldn't see anything like a time, if you can see below image, it only returns 25/12/2013.
I know that people suggested to use pl/sql functions like
to_date()
or
to_char()
but is this possbile using just php? I really can't interfere the SQL. Any help would be awesome, Thanks in advance.
In ADOdb, make sure to set the format before connecting:
$db = ADONewConnection("oci8");
// $db->debug = true;
// Date format is set before connecting.
$db->NLS_DATE_FORMAT = 'DD.MM.YYYY HH24:MI:SS';
Courtesy: http://board.issociate.de/thread/192412/OCI_ignoring_NLS_DATE_FORMAT_parameter.html
You can use SQL functions in your queries as well.
For example,
SELECT TO_CHAR(next_start_date, 'YYYY-MM-DD HH24:MI:SS') FROM mytable
and you'll get the date in the format you specified.
As #Maheswaran Ravisankar pointed out, there is NLS_DATE_FORMAT as well, but if you set it, that format is used for all queries (that do not specify to_char). I always use to_char in all my selects, because it allows me to specify an individual format for each query.
I have a problem in storing the $date variable in the database column called data of type varchar(50)
This is the code of the date variable
$date = date("Y-m-d");
echo $date;
and this is the code that stores it into the database (notice that the date is the same one)
what is the problem with my code
$sql="INSERT INTO
Students(FirstName, LastName,gender,Major,Favorite_courses,GPA,date)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[sex]','$_POST[major]',
'$_POST[favorite]','$_POST[GPA]','$date')";
Change the column type to DATE and then use SYSDATE as the value to input the current date/time on the SQL server.
Also, read up on SQL injection!
Technically your code should work, but in practice it will undoubtedly fail.
For starters you should never put POST data directly into your database. Depending on what's in that data, it will at the least break your SQL statement. It could also destroy your database if someone entered some SQL into a POST variable.
Don't do it that way. You need to sanitize any data coming from the outside world before inserting it into the database. There are several PHP database classes that do this for you. I like PDO.
Also, write better PHP by using $_POST['favorite'] instead of $_POST[favorite]. What happens if you do this in your code somewhere define('favorite', 'foobar')?
What happens is that your code will than look for $_POST['foobar'] instead of $_POST['favorite'].
You really need to work on your knowledge of PHP and SQL before rolling anything out into the wild, or you're going to have problems. But keep plugging along, you'll get it.
Aside from the, already several times mentioned, SQL injection: use date('c') (or more specifically: ISO8601 notation). That will result in code like:
$query = "insert into mytable (myfield) values ('" . date('c') . "')";
Which will result in a query like:
insert into mytable (myfield) values ('2013-06-03T22:20:32+02:00')
This is an unambigious notation and should always work (Y-m-d will work fine too, as per your question, it only stores a date without any time). When using any other notation there's always the problem for the RDBMS that it has to know wether it has to interpret 02/12/1977 as February 12th 1977 or December 2nd 1977. Also, make sure that myfield (in my example) is of type DateTime or Date and not varchar and that you correctly escape reserved words like date in querystrings:
select foo, bar, `date`, foobar from mytable....
However, MySQL seems to 'allow' date (because of "MySQL permits some keywords to be used as unquoted identifiers because many people previously used them." wich is a stupid reason). It's best to just stick to escaping always:
select `foo`, `bar`, `date`, `foobar` from `mytable` ....
Please note that I did not use any sort of MySQLi or PDO prepared statements in this example; you should go read up on SQL injection and then on those topics and then go back to your code.
You can use the php class Date and use his format function
I am using the p4a application framework and I have build several databases one of which needs to gather the date of a booking, I understand that there Isn't a way to do this through MySQL but I haven't found anything useful on the p4a forums on this so anyone that uses the p4a framework that could help, I would be grateful,
I have my local set as en_GB which sets the date within the p4a field as dd-mm-yyyy but I need it to be yyyy-mm-dd to actually write the data into the database,
the present code for this operation is:
$this->build("p4a_field","date")
->setlabel("Date")
->setType('date')
$location = $this->AreaName->getNewValue();
$date = $this->date->getNewValue();
$merono = $this->merono->getNewValue();
$p4a = p4a::singleton();
$p4a->i18n->autoUnformat($date, "shortdate");
p4a_db::singleton()->query("INSERT INTO meetingrooms(location, date, merono)
VALUES
('$location', '$date', '$merono')");
Any help would be appreciated, I was planning on intercepting the function using afterClick but I need to know the syntax required first.
Thanks,
Steve
If I understand correctly, you have some dates in a non-MySQL-friendly format, but you want to use them for INSERTs, right?
How about letting MySQL convert them for you?
SELECT STR_TO_DATE('31-12-2012','%d-%m-%Y');
-> '2012-12-31'
EDITS:
It looks like you have the date:
$date = $this->date->getNewValue();
so you need to use the formula in your SQL:
p4a_db::singleton()->query("INSERT INTO meetingrooms(location, date, merono)
VALUES
('$location', STR_TO_DATE('$date','%d-%m-%Y'), '$merono')");
I'm not a p4a guy, so hopefully that'll work.
Note that, in most languages, you'll be exposed to SQL injection with code like that. Does p4a cover that for you, or provide for positional parameters?
Good luck.
I work on a site where visitors can create an account, and to do so, they have to confirm their email adresses in the end of the process.
Before the account is created, the entered values such as email, pass etcetc are kept in a special table temporarily. That means a visitor has an hour to open their email and klick the link, or else that row will be deleted, to prevent "garbage" from bots and evil or simply overlazy people.
My idea was to let the users clean up the mess, and this is how: when a user klick the link sent to them, the row in the table with temporarily stored values is moved to the actual table for members, and another function will clean up rows that are "outdated", that is, who are inserted more than one hour ago.
This is my current code:
$stmt3 = $dbc->prepare('DELETE FROM temp_storage WHERE time() - time > 3600');
$stmt3->execute();
(time is the column with the time when the row was inserted is stored)
However this code is appareantly not working. I know I could do a workaround with SELECT FROM temp_storage and then check if the row is inserted too long ago, but I thought that, why would it be impossible to do it this way?
Now my question is, is it, or am I doing it the wrong way?
TIME() in MySQL does not give you the current time, it strips the "time portion" from a timestamp. You are looking for a different time function, probably UNIX_TIMESTAMP() if that is how you are storing your timestamps in the table.
Review MySQL date and time functions here: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html
The function you're using to get the current time is not correct. It's not time() it's now().
If you check what $pdo->errorInfo() returns you'll see an error message.
In light of your comments about echo time() i get what you wanted to do but in order for that to work you should have written the following:
$stmt3 = $dbc->prepare('DELETE FROM temp_storage WHERE '.time().' - time > 3600');
$stmt3->execute();
By doing this you're using the return value of PHP's time() function to build a string which will then be sent to MySQL to be executed as a query.
You have to understand the difference between PHP-realm and SQL-realm code:
PHP only constructs text strings. It patches together various words an letters to compose a string. PHP doesn't even care what that string is for.
PHP can never look into that string and say "hey this is some good SQL queries right here".
What it can do is send the text you composed to an SQL server; the sql server will try and execute the text as if if were a corect SQL language statement.
If it hits errors it'll report them back to PHP if not it returns the results to PHP. In any case the SQL statements are strings and they get composed before being actually sent to the server.
"Interrupting" a string and concatenating another string to it such as "me"."&"."you" is just part of the process of building the string before sending it to the SQL server.
Try this:
$stmt3 = $dbc->prepare('DELETE FROM temp_storage WHERE UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(time) > 3600');
I assume the entry_dt column is a datetime column.
where CURRENT_TIMESTAMP - interval 1 HOUR > entry_dt
You should avoid naming columns the same as sql functions and keywords
ref
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
I have several db calls in my site with bind_variables that works fine. But, I can find the correct sign for Date in the documentation, for the command:
$query->bind_param("ssi",...);
I don't want to do something like:
$db->query('SELECT item FROM table WHERE something='.$something);
Since this is string manipulation, not binding. (In binding the query is left with the "?" and that makes the queries faster because the DB sees them the same only with different cariables.)
If I wasn't very clear, I want to do the same as this only with a date variable type.
Some extra information to my comment given above:
If I do understand correctly have a
look at:
Using Mysqli bind_param with date and time columns?.
It looks like you can just treath it
as a string.
If you want to do it with bind_param it is the only way I know to do it and I don't see any problems. If mysql receives a wrong formatted date it will insert a 0000-00-00 value to your table.
Can you tell me what you think could be a problem? If you insert it as a normal query you also use the same syntax as a String.
For dates, you will have to format them before calling bind_param:
$query->bind_param('s', $date->format('Y-m-d H:i:s')); // assuming $date is a DateTime object
Dates should be bound as strings in a format MySQL accepts (yyyy-mm-dd).