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
Related
Im am learning / Training MySQL , PHP I`m beginner at PHP
So i was trying to make a CRUD, so i was trying to save Date in database . so i used input type "DATE" in form. but id didn't worked quite well it just doesn't insert date just saves it as 0000-00-00 (MySQL datatype DATE)
In form:
<input type="date" name="release">
And here.
if (isset($_GET['submit'])) {
$ename= $_GET['name'];
$edate= $_GET['release'];
$eseas= $_GET['season'];
$insert= "INSERT into episodes (name, date, season) values($ename,$edate,$eseas) ";
I am just learning PHP, if there is a better way to do that please recommend me
Thanks in advance :-)
Bug #1: You are vulnerable to sql injection attacks. Go to this link and read and UNDERSTAND the problem before you go any farther
Bug #2: You haven't quoted your values, so your PHP
$sql = "INSERT ... VALUES(...,$edate,...)"
is going to produce this SQL:
INSERT ... VALUES (...,2015-08-20,...)
Since you have no quotes around your date value, it's not really a date. It's a mathematical subtraction, and you're really doing 2015-8-20 => 1987, and the query is extecuted as
INSERT ... VALUES (...,1987,...)
Since 1987 isn't a valid date string (mysql expects yyyy-mm-dd), you get the all-zeroes date in your db.
Ignoring the injection problem, you need:
$insert= "INSERT into episodes (name, date, season) values($ename,'$edate',$eseas) ";
^------^
And similarly for any other field value that isn't a plain number. If you don't quote strings, the strings are interpreted as field/table names, which probably don't exist.
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
It seems like there are too many complicated ways of doing this, so I'm looking for a clean, succinct answer to this issue.
I write a blog, I click submit, and the title, content, and timestamp INSERTS INTO my blog table. Later, the blog is displayed on the blogindex.php page with the date formatted as MM-DD-YYYY.
So this is my 3 step question:
What is the best column type to insert the date into? (ex: INT, VARCHAR, etc)
What is the best INSERT INTO command to use? (ex: NOW(), CURDATE(), etc)
When I query the table and retrieve this data in an array, what is the best way to echo it?
I'm new at PHP/MySQL, so forgive me if I don't know the lingo and am too frustrated reading 1000 differing opinions of this topic that do not address my issue specifically, or only cover one of the 3 questions...
Here is my opinion on your three questions:
Use the correct data type: Date or DateTime. I would choose for the DateTime type as you store the time as well (might be very handy if you want to have some kind of order, when you added the posts).
It all depends whether you just want the Date (use CURDATE()) or the Date + Time (use NOW()).
You fetch the data and format it how you want it. Don't format it yet in the query, just use the correct PHP functions for it (for example with DateTime). How you fetch the data, doesn't matter too much; you can use PDO or MySQLi or ...
Always store and process dates and times in UTC and perform timezone adjustments in your presentation layer - it considerably simplifies things in the long-term.
MySQL provides a number of different types for working with dates and times, but the only one you need to worry about is DATETIME (the DATE type does not store time information, which messes up time zone conversion as information is lost, and the TIMESTAMP type performs automatic UTC conversion (which can mess up programs if the system time zone information is changed) and has a smaller range (1970-2038).
The CURDATE() function returns only the current date and excludes time information, however this returns information in the local timezone, which can change. Avoid this. The NOW() function is an improvement, but again, returns data in the current time zone.
Because you'll want to keep everything in UTC you'll actually want to use the UTC_TIMESTAMP function.
To return the value you'll need to execute SQL commands in sequence with variables, like so:
SET #now = UTC_TIMESTAMP()
INSERT INTO myTable ( utcDateTimeCreatedOrSomething ) VALUES ( #now )
SELECT #now
Date would probably be the best type, although datetime will work as record more accurate as well.
There isn't a 'best insert into', but what do you really want and how accurate you want the date to be. For a blog, I would say make it datetime and use NOW(). so visitors can see quite accurate of when this post is made.
surely you can easily find huge to run sql and fetch a select query from sql using php by google, so I'll leave this easy work to your self.
For echo the date, you can use the php date format such as:
$today = date("m-d-y"); // 03-10-01
I think Styxxy has it pretty well right, but here is a links for your PHP date formatting part...
How to format datetime most easily in PHP?
(Supporting link: http://php.net/manual/en/datetime.format.php )
Basically it's
echo date("d/m/Y", strtotime('2009-12-09 13:32:15'))
... although, I think the strtotime is unnecessary as it should already have the type of datetime.
In terms of the MySQL, yes, do it as a datetime col, use NOW() as the SQL keyword, and depending on how you want to get it from the database you could...
SELECT CAST(col_name AS DATE) .... or .... SELECT CAST(col_name AS DATETIME) <-- this last one is implied due to the col type.
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).