How do I store NULL date in Mysql [duplicate] - php

I am having trouble inserting null values into date fields into a MySQL table.
Here is the insert query:
$query = 'INSERT INTO table (column_s1, column_s2, column_d1, column_d2)
VALUES ("'.$string1.'", "'.$string2.'", '.$date1.', '.$date2.')';
Columns s1 and s2 take string values and d1 and d2 take dates. When I run this query with only the string fields, there is no problem.
The date values can be either set or null, so I have not included the quotation marks in the query, but have instead added them to the variable earlier on. This is the php code I am using to set the date values:
if (empty($date1)){
$date1 = NULL;
}
else{
$date1part = explode("/",$date1);
$date1 = '"'.$date1part[2].'/'.$date1part[1].'/'.$date1part[0].'"';
}
When the date values are all set, the record is inserted correctly. However, when either of the dates is null, nothing is inserted.
Why can't I just insert null values into MySQL like this?

Try this:
$query = "INSERT INTO table (column_s1, column_s2, column_d1, column_d2)
VALUES ('$string1', '$string2', " . ($date1==NULL ? "NULL" : "'$date1'") . ", " . ($date2==NULL ? "NULL" : "'$date2'") . ");";
so for example if you put this into query:
$string1 = "s1";
$string2 = "s2";
$date1 = NULL;
$date2 = NULL;
result should be:
INSERT INTO table (column_s1, column_s2, column_d1, column_d2) VALUES ('s1', 's2', NULL, NULL);

You should convert the null variable into a NULL string first
Like this:
if(is_null($date1)){
$date1 = 'NULL';
}
If you are using a MySQL date column, you must also specify that it should hold null when creating it, like this:
CREATE TABLE `table` (
id INT NOT NULL AUTO_INCREMENT,
date DATE NULL DEFAULT NULL,
PRIMARY KEY(id)
)
It is also very important that you perform the query with bound parameters, for example using pdo
http://www.php.net/manual/en/pdo.construct.php
http://php.net/manual/en/pdo.prepared-statements.php
How do I insert NULL values using PDO?
Something like this:
$query = 'INSERT INTO table (column_s1, column_s2, column_d1, column_d2)
VALUES (?, ?, ?, ?)';
$stmt = $db->prepare($query);
$stmt->execute(array($string1,$string2,$date1,$date2));

If NULL does not work, just pass your date as "0000-00-00":
$chequeDate = "0000-00-00";

Backslash N is another way to express NULL in MySQL.
Try putting the value (backslash N): \N into one of the parameters like this:
$data1 = "\N";
$sql="insert into tablename set column_s1='" . $data1 .
"', column_s2='" . data2 .
"', column_s3='" . $data3 . "'";
Reference: http://dev.mysql.com/doc/refman/5.1/en/load-data.html

In Derby, If you want to insert values except the ones you have declared Null (column_d1, column_d2), sql:
INSERT INTO DB.table (column_s1, column_s2) VALUES ('s1', 's2');

Probably answer is unneeded at this moment, but I found solution exactly I have been searching. Use an Expression to pass NULL like this:
['some_date_to_update' => new Expression('NULL')]
Hence, MySQL will understand what you want, and save (NULL) in DB instead of storing 0-dates. Hope this will help somebody.

In Mysql DATE data type Default NULL means
Some version set as 0000-00-00
Some version set as 1970-01-01

Years later, if someone is still experiencing this issue, you want to use PDO and bind the variables, everything will be taken care of no need to handle the null variables yourself.

Related

PHP MYSQL, 1292: Incorrect date value: '' for column 'sale_date' at row 1

I have a MySQL database with a clients table and a person(used for testing) table. My HTML, PHP, and scripts work as expected in the person table. When using the same coding in my clients table I get the following error "1292: Incorrect date value: '' for column 'sale_date' at row 1.
My HTML code is as follows:
<label>Sale Date:&nbsp <input id="cSaleDate" class="cSale" type="date" name="cSaleDate"></label>
My PHP code:
$sale_date = mysqli_real_escape_string($db,$_POST['cSaleDate']);
if (isset($_POST['cSaleDate']))
{
include_once('client.php');
$saleDate = date('0000-00-00', strtotime($sale_date));
if (!empty($_POST['cSaleDate']))
{
$saleDate = date('Y-m-d', strtotime($sale_date));
}
}
$fields = 'fips_code, size_code, client_name, client_state, sale_date';
$values = "'$fips_code', '$size_code', '$client_name', '$client_state', '$saleDate'";
$sql = "INSERT INTO clients ($fields) VALUES ($values)";
The column for the sale date is set as:
Name: sale_date
Datatype: DATE
Default: NULL
As mentioned before, this code does work with dates in the "person" table, but not with the "clients" table. I have the date column setup the same on both tables. Any help or ideas on why this works for one table but not the other would be greatly appreciated.
Your code largely depends on $_POST['cSaleDate'] and from the snippet you've provided if you don't actually get that value then $saleDate would be undefined. That is my best guess at what the problem may be.
Here is a possible way to rewrite that snippet:
// It seems you want this as your default if there is no $_POST['cSaleDate']?
$saleDate = '0000-00-00';
// Now check if you should overwrite this default
if (isset($_POST['cSaleDate'])) {
include_once('client.php');
if ( ! empty($_POST['cSaleDate'])) {
$saleDate = date('Y-m-d', strtotime($_POST['cSaleDate']));
}
}
// Now do your escape and db insert
$saleDate = mysqli_real_escape_string($db, $saleDate);
$fields = 'fips_code, size_code, client_name, client_state, sale_date';
$values = "'$fips_code', '$size_code', '$client_name', '$client_state', '$saleDate'";
$sql = "INSERT INTO clients ($fields) VALUES ($values)";
Thanks all for the help. I ended up using a ternary statement in the insert, which allowed me to insert 'NULL' into the date field in the database if the input is left blank.
$sql = "INSERT INTO table (SaleDate) VALUES (" . ($saleDate == '' ? 'NULL' : "'$saleDate'") . ")"

I cannot insert a word to mysql

if(isset($_POST['zodis'])) {
strpos($_POST['zodis'], ' ');
if($pos > 0) {
print '<h2> Only 1 word. </h2>';
} else {
$query = "INSERT INTO `zodziai` (`id` ,`zodis` ,`date`)VALUES (NULL , '"$_POST['zodis']"',CURRENT_TIMESTAMP);";
mysql_query($query) or die(mysql_error());
}
}
Where i made a mistake? Im new in PHP
it shows
Parse error: syntax error, unexpected T_VARIABLE in
C:\wamp\www\php_mysql.php on line 19
You forgot the ..
$query = "INSERT INTO `zodziai` (`id` ,`zodis` ,`date`)VALUES (NULL , '" . $_POST['zodis'] . "',CURRENT_TIMESTAMP);";
$query = "INSERT INTO zodziai (id,zodis,date)VALUES (NULL, '".$_POST['zodis']."',".time().");";
your id field isn't autoincreament?
what kind of type field is your date field?
If you mix strings and variables, you should use "." to concatenate them:
...VALUES (NULL , '".$_POST['zodis']."',CURRENT_TIMESTAMP)...
(Note the point (.) before and after $_POST variable).
That is what I've seen taking a fast look, maybe there is something more.
You are not initializing $pos. Try this :
$pos = strpos($_POST['zodis'], ' ');
You have also forgotten the concatenation operator (.), in your query.
$query = "INSERT INTO `zodziai` (`id` ,`zodis` ,`date`)VALUES (NULL , '" . $_POST['zodis'] . "',CURRENT_TIMESTAMP);";
Also avoid using mysql_ functions, PHP discourages using mysql_ functions and mysql_ functions will soon be deprecated, rather, use mysqli class or PDO.
Another suggestion, rather than sending CURRENT_TIMESTAMP in the query, create the table field using the following constraint
`date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
and then pass NULL in the query, this will automatically set the date field in the corresponding row as CURRENT_TIMESTAMP.

How to get just inserted row from MySql to a php variable?

I'm using Zend Framework and MySql to create my web-application. My SQL-code is the following at the moment:
public static function newTestResult($testId, $accountId, $score, $deviation, $averageTime)
{
try
{
$db = self::conn();
$statement = "INSERT INTO test_results(test_id, test_person_id, score, standard_deviation, average_answer_time, created_at)
VALUES(" . $testId . ", " . $accountId . ", " . $score . ", " . $deviation . ", " . $averageTime . ", NOW())";
$db->query($statement);
$db->closeConnection();
}
catch(Zend_Db_Exception $e)
{
error_log($e->getMessage());
}
}
Now what I'm asking is: How can I get the just inserted row to a variable in PHP? I would want to get my hands on the id-value what MySql is creating automatically for the row.
Here is my table code:
CREATE TABLE test_results(
id int UNSIGNED AUTO_INCREMENT PRIMARY KEY,
test_id int UNSIGNED NOT NULL,
test_person_id int UNSIGNED NOT NULL,
score float UNSIGNED NOT NULL,
standard_deviation float UNSIGNED NOT NULL,
average_answer_time float UNSIGNED NOT NULL,
removed boolean NOT NULL DEFAULT 0,
created_at datetime) CHARACTER SET utf8 COLLATE utf8_general_ci;
Take a look at the MySQL function "LAST_INSERT_ID()"
See also this forum for more detail on the methods available.
http://forums.phpfreaks.com/topic/188084-get-last-mysql-id-using-zend-frameworks/
In "plain" PHP, I usually use the mysql_ functions. The mysql_insert_id() function returns the key of the last row inserted. I'm not advocating this over using the Zend way, just giving context:
mysql_query("INSERT INTO ... query");
$id = mysql_insert_id();
Then reference that ID in writing other queries related to that inserted row.
This should give you the last insert id from the last query made.
$db->lastInsertId()
try this:
$query="SELECT id FROM test_results WHERE test_id=$testId";
$id=$db->query($query);
I assume this is what you're looking for, otherwise you can change the WHERE condition to whatever you need.
From the MySQL manual: "If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id() function." This refers to the C function.
In the PHP manual, you are suggested to use the PDO function instead. http://php.net/manual/en/function.mysql-insert-id.php PDO::lastInsertId
And apparently, "The insert() method on Zend_Db_Table will return the value of the last insert id." http://osdir.com/ml/php.zend.framework.db/2007-04/msg00055.html
To get last two records from any table you can use the following query
SELECT * FROM aa WHERE ID IN(
(SELECT COUNT(*) FROM aa),
(SELECT COUNT(*) FROM aa)-1
)

MySQL int column allows null but enters null as zero

I've looked around and have noticed a few people have had the same problem but their oversight doesn't seem to apply here.
I have a PHP function to add an array of values into a table. It first checks whether the values are empty and if so replaces them with NULL, in order to place a null in the table field. Each fields that I'm placing null into allows for null yet places a 0 there instead.
Here's some code:
public static function AddGame($array, $tId)
{
global $db; // Bring DB into scope
// Get IDs from particular names
$locId = $array['fLocation'];
// Ensure empty values are SQL null
$hTeamId = "'{$array['fHomeTeam']}'";
$vTeamId = "'{$array['fVisitTeam']}'";
$hScore = "'{$array['fHomeScore']}'";
$vScore = "'{$array['fVisitScore']}'";
$hHoldFor = "'{$array['fHomeHoldFor']}'";
$vHoldFor = "'{$array['fVisitHoldFor']}'";
// Prepare row for insertion
$row = "'','$tId','$locId',$hTeamId,$vTeamId,'{$array['fDate']}','{$array['fTime']}',$hScore,$vScore,'{$array['fGameType']}',$hHoldFor,$vHoldFor";
$stmt = $db->prepare("INSERT INTO `game` VALUES($row)");
if($stmt->execute()) return true;
else return false;
}
I've debugged this function at various lines and have dumped the $row string and it shows this, which is expected:
'','1','1','21','21','10/10/12','10:30AM','NULL','NULL','pool','NULL','NULL'
Yet when I check the table text type fields literally have the value NULL which is not what I want and also int fields show as 0. If I leave the values blank or as PHP's null then text fields show as empty (or properly null as I'd like) yet the ints still show as 0.
I expect this is only caused due to the way I insert the values indirectly.
Here is the SHOW CREATE TABLE game
CREATE TABLE `game` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`tId` int(11) NOT NULL,
`Lid` int(11) NOT NULL,
`hTeamId` int(11) DEFAULT NULL,
`vTeamId` int(11) DEFAULT NULL,
`date` text NOT NULL,
`time` text NOT NULL,
`hScore` int(11) DEFAULT NULL,
`vScore` int(11) DEFAULT NULL,
`type` text NOT NULL,
`hHoldFor` text,
`vHoldFor` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=latin1
UPDATE:
INSERT INTO `game` VALUES('','1','1','','','10/09/12','9:30AM','','','pool','winner of pool A','winner of pool B')
You are physically setting the value of the wanted NULL columns to a string of 'NULL'
NULL != 'NULL'
If you set your table structure for those columns to NULL, you can omit them from your query and they will automatically be NULL on insert.
Do this instead:
if(!empty($hHoldFor)) $hHoldFor = $array['fHomeHoldFor'];
Update
I was looking further into your example and there is a second point of failure.
$row = ... ",'$hHoldFor','$vHoldFor'";
The above line, if you set $hHoldFor = NULL, will insert quotes around NULL, turning it back into a string of NULL.
Try this:
if(!empty($hHoldFor)) $hHoldFor = "'{$array['fHomeHoldFor']}'";
...
$row = ... ",$hHoldFor,$vHoldFor";
This removes the single quotes around this value in the QUERY string and adds them to the variable itself.
Update 2
Here is an SQLFiddle using your schema. It returns NULL for NULL columns. Can you do an echo "INSERT INTOgameVALUES($row)"; and post the output? The issue is PHP is converting the NULL to 'NULL' still somewhere. This will help us get to the bottom of it.
Update 3
The issue is just as thought. Your PHP is inserting a blank string, '', into your database, which is not a NULL value. NULL is of a type, '' is a string with no length.
INSERT INTO `game` VALUES('','1','1','','','10/09/12','9:30AM','','','pool','winner of pool A','winner of pool B')
Try this:
public static function AddGame($array, $tId)
{
global $db; // Bring DB into scope
// Get IDs from particular names
$locId = $array['fLocation'];
// Ensure empty values are SQL null
$hTeamId = (strlen($array['fHomeTeam']) != 0 ? "'{$array['fHomeTeam']}'" : 'NULL');
$vTeamId = (strlen($array['fVisitTeam']) != 0 ? "'{$array['fVisitTeam']}'" : 'NULL');
$hScore = (strlen($array['fHomeScore']) != 0 ? "'{$array['fHomeScore']}'" : 'NULL');
$vScore = (strlen($array['fVisitScore']) != 0 ? "'{$array['fVisitScore']}'" : 'NULL');
$hHoldFor = (strlen($array['fHomeHoldFor']) != 0 ? "'{$array['fHomeHoldFor']}'" : 'NULL');
$vHoldFor = (strlen($array['fVisitHoldFor']) != 0 ? "'{$array['fVisitHoldFor']}'" : 'NULL');
// Prepare row for insertion
$row = "'','$tId','$locId',$hTeamId,$vTeamId,{$array['fDate']}','{$array['fTime']}',$hScore,$vScore,'{$array['fGameType']}',$hHoldFor,$vHoldFor";
$stmt = $db->prepare("INSERT INTO `game` VALUES($row)");
if($stmt->execute()) return true;
else return false;
}
You can't insert 'NULL'. Remove the single quotes around NULL.
Your string
'','1','1','21','21','10/10/12','10:30AM','NULL','NULL','pool','NULL','NULL'
Should look like
'','1','1','21','21','10/10/12','10:30AM',NULL,NULL,'pool',NULL,NULL
You should also define a column list whenever making an INSERT (ie. INSERT INTO table (col1, col2) VALUES ...)
Edit 1
I would recommend looking through your SHOW CREATE TABLE tbl_name
Edit 2
After testing this, I would still say the problem is with how you're inserting the data.
(18,1,1,21,21,'10/10/12','10:30AM',NULL,NULL,'pool',NULL,NULL)
Works.
('18','1','1','21','21','10/10/12','10:30AM','NULL','NULL','pool','NULL','NULL')
Does not work: Incorrect integer value: 'NULL' for column 'hScore' at row 1:
Edit 3
Here is an improved version of your class:
public static function AddGame($array, $tId)
{
global $db; // Bring DB into scope
// Get IDs from particular names
$locId = $array['fLocation'];
// Ensure empty values are SQL null
$hTeamId = empty($array['fHomeTeam']) ? 'NULL' : "'" . $array['fHomeTeam'] . "'";
$vTeamId = empty($array['fVisitTeam']) ? 'NULL' : "'" . $array['fVisitTeam'] . "'";
$hScore = empty($array['fHomeScore']) ? 'NULL' : "'" . $array['fHomeScore'] . "'";
$vScore = empty($array['fVisitScore']) ? 'NULL' : "'" . $array['fVisitScore'] . "'";
$hHoldFor = empty($array['fHomeHoldFor']) ? 'NULL' : "'" . $array['fHomeHoldFor'] . "'";
$vHoldFor = empty($array['fVisitHoldFor']) ? 'NULL' : "'" . $array['fVisitHoldFor'] . "'";
// Prepare row for insertion
$row = "$tId,$locId,$hTeamId,$vTeamId,'{$array['fDate']}','{$array['fTime']}',$hScore,$vScore,'{$array['fGameType']}',$hHoldFor,$vHoldFor";
$stmt = $db->prepare("INSERT INTO game (tId, Lid, hTeamId, vTeamId, date, time, hScore, vScore, type, hHoldFor, vHoldFor) VALUES($row)");
if($stmt->execute()) return true;
else return false;
}
Non-NULL values will be encased in quotes, otherwise they are assigned NULL. I've also defined the column list for INSERT and excluded id, as it's an AUTO_INCREMENT column.
Does you column allows NULL values? Check the DDL again maybe you have set the DEFAULT VALUE to zero.
When you try to insert null value in a column, don not wrap it with single quote. Example
INSERT INTO tableName (colName, ColNameB) VALUES (1, NULL)
In my case i had to display three situations: Case-empty, Case-yes and Case-no. I planned to use null, one and zero. But the null was being saved always as 0. The column i was working accepted null entries but all my nulls was being saved as zeros.
My solution, was considering Case-empty as zero, Case-yes as the number one and case-no as the number two. It is a workaround but solved the problem.

Insert a datetime with prepared statement [duplicate]

This question already has answers here:
Using Mysqli bind_param with date and time columns?
(5 answers)
Closed 1 year ago.
I am trying to use prepared statements to insert a datetime for a library application. Here is the code thus far:
global $dbh;
$query = "INSERT INTO `loan` SET
`title` = (?), //example value - Lord of the Rings
`description` = (?), //example value - Trilogy
`start_date` = (?), //example value 20120701 in String datatype
`end_date` = (?)"; //example value 20120702 in String datatype
$statement = $dbh->prepare($query);
$statement->bind_param("ssss", $title,$description,$startDate,$endDate);
$statement->execute();
print $statement->error; //to check errors
$statement->close();
However, I cannot seem to insert this value into the row. At the same time, somehow the
print $statement->error
does not seem to display any error.
Any help will really do.
UPDATE:
It actually works. I was just referencing the wrong database. But I want to add a little outro for new people who chanced upon this.
Remove all the comments as mentioned in the comments/answers as they will mess up your string.
For DATETIME, remember to specify the datatype as String as MySQL only recognises String datatype. If you are not using prepared queries, this means you have to add '' quotes for the values.
The insertion will result in the date (2012-07-01 00:00:00) format as time is not specified.
Both SQL queries work. INSERT INTO tbl_name SET col_name = value or INSERT INTO tbl_name(col_name) VALUES (value) work.
Try something like this:
global $dbh;
$query = "INSERT INTO loan (title, description, start_date, end_date) VALUES (?,?,?,?)"
$statement = $dbh->prepare($query);
$statement->bind_param("ssss", $title,$description,$startDate,$endDate);
$statement->execute();
print $statement->error; //to check errors
$statement->close();
Assuming your form input for your date is a type input named "date", here is what you do. In php type
$date = $_POST['date']
$query = "INSERT INTO `loan` SET
`title` = (?),
`description` = (?),
`start_date` = ".$date. //Insert variable here
"`end_date` = (?)";
I know it's not good practice to insert a date in one single type input but I am just using this example for simplicity only. The proper way you can figure out yourself.

Categories