Php insert null date

Как хранить значения NULL в полях datetime в MySQL?

У меня есть поле «bill_date», в котором я хочу быть пустым (NULL), пока он не будет выставлен счет, после чего будет введена дата. Я вижу, что MySQL не любит значения NULL в полях datetime. У любого из вас есть простой способ справиться с этим, или я вынужден использовать минимальную дату как «эквивалент NULL», а затем проверить эту дату? Спасибо. ИЗМЕНИТЬ ДОБАВИТЬ: Хорошо. Я вижу, что MySQL будет принимать значение NULL, но он не примет его в качестве обновления базы данных, если я обновляю запись с помощью PHP. Имя переменной $bill_date , но она не оставит переменную как NULL, если я обновляю запись без отправки значения $bill_date — я получаю эту ошибку:

Database query failed: Incorrect datetime value: '' for column 'bill_date' at row 1 

Я предполагаю, что мне нужно на самом деле отправить слово NULL или вообще оставить его вне запроса на обновление, чтобы избежать этой ошибки? Я прав? Спасибо.

MySQL DOES принимает нулевые значения для определения даты и времени, но если по какой-то причине вы думаете иначе и не будете использовать нулевое значение, попробуйте просто использовать «1000-01-01» в качестве значения и исключить строки, которые имеют это значение для вашего bill_date столбец в ваших запросах.

Mysql допускает пустые значения в полях datetime. Я подозреваю, что проблема связана с тем, как вы получаете доступ к MySQL. Не могли бы вы отредактировать свой вопрос с помощью механизма, который вы используете для доступа к данным? Например, вы используете мой ODBC, библиотеку Perl и т. Д.?

Используйте NULL (без единой косой черты) вместо » в ваших запросах, чтобы добавить значение NULL в поле datetime.

8 ответов

MySQL не позволяет значения NULL для полей datetime . Я просто протестировал его:

mysql> create table datetimetest (testcolumn datetime null default null); Query OK, 0 rows affected (0.10 sec) mysql> insert into datetimetest (testcolumn) values (null); Query OK, 1 row affected (0.00 sec) mysql> select * from datetimetest; +------------+ | testcolumn | +------------+ | NULL | +------------+ 1 row in set (0.00 sec) 
mysql> select version(); +-----------+ | version() | +-----------+ | 5.0.45 | +-----------+ 1 row in set (0.03 sec) 

РЕДАКТИРОВАТЬ № 1: в вашем редактировании я вижу, что сообщение об ошибке, которое вы получаете на PHP, указывает, что вы передаете пустую строку (т.е. » ), а не NULL . Пустая строка отличается от NULL и не является допустимым значением datetime , поэтому вы получаете это сообщение об ошибке. Вы должны передать специальное ключевое слово sql NULL , если это то, что вы имеете в виду. Кроме того, не помещайте никаких кавычек вокруг слова NULL . См. Мой оператор insert выше для примера того, как вставить NULL .

Читайте также:  Background Color: body gbcolor

РЕДАКТИРОВАТЬ № 2: Вы используете PDO? Если это так, когда вы связываете свой нулевой параметр, не забудьте использовать тип [PDO::PARAM_NULL][1] при привязке NULL . См. https://stackoverflow.com/questions/1391777/how-do-i-insert-null-values-using-pdo о том, как правильно вставить NULL с помощью PDO.

@Jason Джейсон Роудс: Хорошо, я обновил свой ответ, чтобы исправить ваши правки. Если вы все еще не можете заставить его работать, опубликуйте свой код PHP.

@Jason Джейсон Роудс: я включил несколько советов, которые могут быть полезны, если вы используете PDO.

Я догадываюсь, что имеет смысл. Я не использую PDO (и на самом деле не знаю, что это такое!). Я не могу передать NULL легко, потому что я использую стандартный метод объекта для обновления. Мне нужно переделать некоторые вещи.

Нулевая дата не является нулевой датой. Они могут выглядеть одинаково, но это не так. В mysql значение нулевой даты равно null. Значение нулевой даты — это пустая строка (») и ‘0000-00-00 00:00:00’

В нулевой дате «. где mydate = »» не будет выполнено.
В пустой/нулевой дате «. где mydate is null» не удастся.

Но теперь давайте фанки. В датах mysql пустая/нулевая дата строго одинакова.

select if(myDate is null, 'null', myDate) as mydate from myTable where myDate = ''; select if(myDate is null, 'null', myDate) as mydate from myTable where myDate = '0000-00-00 00:00:00'

будет выводиться BOTH: ‘0000-00-00 00:00:00’. если вы обновите myDate с помощью » или ‘0000-00-00 00:00:00’, оба варианта будут работать одинаково.

В php тип дат типа mysql будет соблюдаться со стандартным соединителем mysql и быть действительными значениями null ($ var === null, is_null ($ var)). Пустые даты всегда будут отображаться как «0000-00-00 00:00:00».

Я настоятельно рекомендую использовать только нулевые даты, или только пустые даты, если вы можете. (некоторые системы будут использовать «виртуальные» нулевые даты, которые являются действительными григорианскими датами, такими как 1970-01-01 (linux) или 0001-01-01 (oracle).

пустые даты проще в php/mysql. У вас нет поля «where field null» для обработки. Однако вам нужно «вручную» преобразовать дату ‘0000-00-00 00:00:00’ в » для отображения пустых полей. (для хранения или поиска у вас нет специального случая для обработки нулевых дат, что приятно).

Нулевые даты требуют лучшего ухода. вы должны быть осторожны при вставке или обновлении, чтобы НЕ добавлять кавычки вокруг нуля, иначе вместо нулевой будет вставлена ​​нулевая дата, что приведет к хаосу стандартных данных. В формах поиска вам нужно будет обрабатывать такие случаи, как «и mydate не равно null» и т.д.

Нулевые даты обычно больше работают. но они намного МНОГО МНОГО быстрее, чем нулевые даты для запросов.

Источник

Php – MySQL, how to insert null dates

I am having trouble inserting null values into date fields into a MySQL table.

$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.

Читайте также:  Генерация кода python нейросеть

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:

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?

Best Solution

$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; 
INSERT INTO table (column_s1, column_s2, column_d1, column_d2) VALUES ('s1', 's2', NULL, NULL); 
Php – How to prevent SQL injection in PHP

The correct way to avoid SQL injection attacks, no matter which database you use, is to separate the data from SQL, so that data stays data and will never be interpreted as commands by the SQL parser. It is possible to create SQL statement with correctly formatted data parts, but if you don’t fully understand the details, you should always use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.

You basically have two options to achieve this:

    Using PDO (for any supported database driver):

 $stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name'); $stmt->execute([ 'name' => $name ]); foreach ($stmt as $row) < // Do something with $row >
 $stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?'); $stmt->bind_param('s', $name); // 's' specifies the variable type => 'string' $stmt->execute(); $result = $stmt->get_result(); while ($row = $result->fetch_assoc()) < // Do something with $row >

If you’re connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (for example, pg_prepare() and pg_execute() for PostgreSQL). PDO is the universal option.

Correctly setting up the connection

Note that when using PDO to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:

$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'password'); $dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

In the above example the error mode isn’t strictly necessary, but it is advised to add it. This way the script will not stop with a Fatal Error when something goes wrong. And it gives the developer the chance to catch any error(s) which are throw n as PDOException s.

What is mandatory, however, is the first setAttribute() line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren’t parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).

Читайте также:  Java util date string example

Although you can set the charset in the options of the constructor, it’s important to note that ‘older’ versions of PHP (before 5.3.6) silently ignored the charset parameter in the DSN.

Explanation

The SQL statement you pass to prepare is parsed and compiled by the database server. By specifying parameters (either a ? or a named parameter like :name in the example above) you tell the database engine where you want to filter on. Then when you call execute , the prepared statement is combined with the parameter values you specify.

The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn’t intend.

Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name variable contains ‘Sarah’; DELETE FROM employees the result would simply be a search for the string «‘Sarah’; DELETE FROM employees» , and you will not end up with an empty table.

Another benefit of using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.

Oh, and since you asked about how to do it for an insert, here’s an example (using PDO):

$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)'); $preparedStatement->execute([ 'column' => $unsafeValue ]); 

Can prepared statements be used for dynamic queries?

While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features cannot be parametrized.

For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values.

// Value whitelist // $dir can only be 'DESC', otherwise it will be 'ASC' if (empty($dir) || $dir !== 'DESC')
Javascript – How to check for an empty/undefined/null string in JavaScript

If you just want to check whether there’s a truthy value, you can do:

If you need to check specifically for an empty string over null, I would think checking against «» is your best bet, using the === operator (so that you know that it is, in fact, a string you’re comparing against).

Источник

Оцените статью