function showing warnings in mysql that data truncate for column - php

I am using function for UTC timestamp value. function(NOW(),19800);
19800 is offset value that I have calculate before. When I use tis function near insert query ->
insert into Table_nm values('function(NOW(),19800)');
Table_nm contain DateTime field.but when I insert query,It has inserted but inserting 0000-00-00 and 00:00:00 value. Shows warnings that,
Data truncated for column 'Column_nm' at row 1orOut of range value for column 'Column_nm' at row 1`
I have check function separately by
select function(NOW(),19800);
yes, It works. But It does not work in insert syntax.

You are using function(NOW(),19800) within quotes. If you use within quotes it is treated as string. You can use it without quotes in the insert statement, like you did while checking the select statement.

Related

How to insert empty string into a date column using PDO?

I am using a PDO prepared statement to insert values. One of the values is a date, and sometimes it can be empty. In MySQL schema, the date column is set to allow NULL values.
Let's assume date_column is a date and it allows NULL. When I do this:
$query = "INSERT INTO tbl(date_column) VALUES(?)";
$stmt = $pdo->prepare($query);
$stmt->execute(['']);
This is giving me this error:
SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '' for column 'date_column' at row 1
In phpMyAdmin, I can execute this query without errors. It sets the date to 0000-00-00
INSERT INTO tbl(date_column) VALUES('')
Isn't that the same query that is executed by PDO behind the scenes in the code example above? What's wrong?
All I want is to be able to insert empty string '' as a date without errors. I don't care if it is set to 0000-00-00
This is too long for a comment.
This is a fundamental problem:
All I want is to be able to insert empty string '' as a date.
Strings are strings, and dates are dates. You should not want to insert an empty string into the column because that makes no sense. Instead, you should want to insert either a NULL value or the default value.
So, your code should look like:
INSERT INTO tbl(date_column)
VALUES(NULL)
or:
INSERT INTO tbl(date_column)
VALUES(DEFAULT)
The fact that MySQL does better type checking on prepared queries with parameters is actually a good thing.
Empty string is not a null... NULL is a NULL
$stmt->execute([null]);

MYSQL and PHP INSERT NULL values

lets say my table only has these members - id (key) and date (which defaults to NULL) .
Now when I want to insert a row with my php , do I need to check before my query whether date has a value or not or can I just insert like so -
$query = "INSERT INTO mytable VALUES(3,{$_GET['date]})"
And mysql would assign a NULL value to date ?
And does this hold true to a table no matter how large ?
e.g : can I insert many values that come from php and may be empty(or null) to a table , and mysql would automatically assign NULL to them (if I defined them as NULL by default of course) or do I need to do all kinds of checks before my inserts?
No, it will assign the value passed with the parameter $_GET['date']. If the value is empty '' and the date was of data type varchar it will insert a value of '' which is different than NULL then it will insert an empty. Thats because NULL and empty strings are not equal. They are two different things in SQL.
If you want to insert NULL values, either ignore this column in the insert columns list, then it will assigned with the default value which is NULL. Or write it explicitly in the values of the INSERT statement.
Note that: Your code this way is vulnerable to SQL injection. You should use prepared statements or PDO instead. See this for more details:
Best way to prevent SQL injection?
This might be relevant and this would also make sure you are not vulnerable to sql injection attacks.
I'd say to just check each variable personally, then you have way more control over your variables before they are getting put in your database.
Try this
$query = "INSERT INTO mytable VALUES(3,'".$_GET['date']."')";
But also consider the datatype of your table field if its set to date/datetime then, check the return value of $_GET['date'] it must also in form of date.
That snippet is wide open to SQL injection. Escape your values or use prepared statements!
If the variable contains nothing, the query will look like ... VALUES (3,). That's a syntax error, so it doesn't work.
If you'd change this to VALUES(3, '{$_GET['date']}')", so in the case of an empty variable the query would be ... VALUES(3, ''), an empty string is the value. That will be cast to some sane value for the column in question, in case of a date column, to an unrecognized date. That's not NULL.
NULL only applies if you omit the column entirely from a query or explicitly set it to NULL. In any other case, the value will be something other than NULL.
$date = date("d-m-Y",strtotime($_GET['date']));
if(isset($date))
$query = "INSERT INTO mytable VALUES(3,$date)";

Can mssql_query detect inserting error?

I am trying to detect inserting result.
When I tried to insert with INSERT INTO table (1,2,'t') this will result in inserting error because of the third column of my table is decimal type,but mssql_query will return true.
but when I tested with INSET INTO table (1,2,'t') this will return false,like it should.
Why the first statement returning true? and how can we check that it is an error not true!!
Correct syntax is:
insert into table_name (column_name1, column_name2, ..)
VALUES (value_of_column1, value_of_column2, ..)
As you already know ordering part is not required, but i highly suggest you to do ordering first and then give values to it.
mysql_query return false on error and you can get error by using mysql_error function.
And keep this in your mind that you should surround values by quotations only when you are filling columns with type of varchar/char/date/datetime..
Other types like boolean, int, decimal and.. should be provided without quotations.
Hope it solve your problem ;)

insert null date / time into mysql with php causing 0000-00-00 / 00:00:00

i see a couple of questions on here and elsewhere that address this in some cases, but not quite what i need.
i am working with a script that stores an array of values to do either an insert or update based on changes.
some dates/times are set and some are null. i am trying with $var=NULL, then inserting with insert into ... ('{$var}') and getting 00:00:00 for the time if null and the time if time is set.
inserting with $var="NULL" and insert into ... ('{$var}') and getting 00:00:00 if null and the time if time is set.
if i remove the quotes for the insert ... ({$var}) it works if null, but if the date is not null, it of course fails.
i have another VARCHAR field i am doing the same thing with and it works fine. i.e. if there is a string it is passed in as a string and if it's empty i am setting that var=null. i am using quotes on the insert query and if it's null, it goes in as null and if not null, the string inserts.
using a conditional statement is going to require a pretty big rewrite, so i am hoping to avoid that.
any suggestions on how to make this work without IF statements (if possible), would help out.
thanks.
i have tested this several ways and i am not able to get the desired results without making the date/time fields VARCHAR, which i don't want to do. here is the db structure, insert queries and results.
id int(11) No None AUTO_INCREMENT
event_new_date_start date Yes NULL
event_new_time_start time Yes NULL
event_link varchar(150) latin1_swedish_ci Yes NULL
$event_new_date_start1 = 'NULL';
$event_new_time_start1 = 'NULL';
$event_link1 = 'NULL';
$event_new_date_start2 = '2011-04-04';
$event_new_time_start2 = '13:13';
$event_link2 = 'http://abc.com';
$event_new_date_start3 = NULL;
$event_new_time_start3 = NULL;
$event_link3 = NULL;
mysql_query("
insert into test_dates (event_new_date_start, event_new_time_start, event_link) values
('{$event_new_date_start1}', '{$event_new_time_start1}', '{$event_link1}')
");
mysql_query("
insert into test_dates (event_new_date_start, event_new_time_start, event_link) values
('{$event_new_date_start2}', '{$event_new_time_start2}', '{$event_link2}')
");
mysql_query("
insert into test_dates (event_new_date_start, event_new_time_start, event_link) values
('{$event_new_date_start3}', '{$event_new_time_start3}', '{$event_link3}')
");
1 0000-00-00 00:00:00 NULL
2 2011-04-04 13:13:00 http://abc.com
3 0000-00-00 00:00:00
when i changed the date/times fields to CHAR, it worked as expected using quotes in the query.
4 NULL NULL NULL
5 2011-04-04 13:13 http://abc.com
6
If you're using quotes, then you're saying that you want the date to be the string 'NULL'. MySQL cannot parse that to a valid date, therefore it falls back to 0.
When setting the value of $var, set it to either just NULL or a quoted string if it's not null, then simply use ({$var}) in the query instead of ('{$var}').
rdineiu is right, the problem is that you are inserting the word "null". MySQL doesn't understand that and so instead of giving an error (like many DBs would), it inserts a time of all zeros. This is especially fun in Java since trying to read that value will cause an exception to be thrown.
The best thing to do is to move to parameterized SQL queries using DBO. You can find a little more and some links with this question and answer on SO. This will not only solve your problem, but it will solve (some) SQL injection problems that could occur with other values being inserted and read back.
Without doing that (which, again, you should and is the correct answer), you could do the insert without the quotes ("({$var})"), and run the date through a function that appends the necessary quotes if it isn't null. But this won't protect you if you get date values directly from users, and you'll have this same problem if you have a string field you want to be nullable.
MySQL often does completely stupid stuff like this; see this useful list of MySQL "gotchas". In this case, I expect that your date field is NOT NULL and your SQL compliance mode is not very strict; this causes MySQL to enter a default date of 0 instead of the NULL that you actually asked it to do. Change your schema to have your date field DEFAULT NULL and this should go away.
Note that this will work if you make the change that the others suggested, e.g. insert NULL not a quoted 'NULL'.

PHP: Inserting the current timestamp into SQL Server 2005

How do I insert a current_timestamp into an SQL Server 2005 database datable with a timestamp column?
It should be simple but I cannot get it to work. Examples would be much appreciated.
if you can execute a query from PHP then it should just be a matter of using 'getdate()' ;
update MyTable set MyColumn=getdate();
or
insert into MyTable (MyColumn) values (getdate());
The column datatype should be datetime
You can either get the database to work out the date:
$sql = 'INSERT INTO tablename (fieldname) VALUES (getdate())';
or get PHP to work out the date
$sql = 'INSERT INTO tablename (fieldname) VALUES (\'' . date('Y-m-d H:i:s') . '\')';
then something like mssql_execute($sql); but this depends on how you are connecting to your database
To insert data into a timeStamp field, I think you have to use DEFAULT.
For example:
INSERT INTO User(username, EnterTS) VALUES ('user123', DEFAULT)
where EnterTS is a TimeStamp field
You just use the normal mechanism to execute your queries into SQL Server, and use what follows.
The current_timestamp function returns it
insert into table (creation_date) VALUES (current_timestamp)
Complete example
CREATE table timestamp_test (creation_timestamp datetime)
INSERT INTO timestamp_test (creation_timestamp) VALUES (current_timestamp)
SELECT * FROM timestamp_test
DROP TABLE timestamp_test
If you explain the error you are receiving (and post your insert or update code), it might make it easier to see what your problem is. One possible issue is that you must be inserting into a datetime field (or in 2008 you could use a date field as well). Occasionally people think that they can insert the current date into a timestamp field but even though the name of this data type seems as if it should be date related, this data type actaully has nothing to do with dates and times and cannot accept date data.
I realize this is an old post but I ran across this and figured others might too.
What I do is to create a field in the table using the datatype of datetime and then for the column properties for the default Value or binding, I enter getdate(). Every record that gets entered into the table now has a date and time stamp.

Categories