How to INSERT NULL value from PHP? - php

Let x is a column of the table t allowing NULL values.
Which value should $value variable take for the following PDO statement to insert NULL value?
$db->prepare("INSERT t SET x=:x")->execute(array(':x'=>$value));

You simply insert it as null:
$db->prepare("INSERT t SET x=:x")->execute(array(':x'=>null));
If you want, you can also add the data type of PDO::PARAM_NULL.

This was asked 9 years ago, so it may no longer be relevant, but SeanWM's existing answer, while it works, does not technically answer specifically what was asked because it does not assign any value to a variable.
Just for completeness:
Inserting the PHP null value into MySQL does result in NULL being inserted into the DB.
$value = null;
$sql = $db->prepare("INSERT t SET x=:x")->execute(array(':x'=>$value));
Output:
Note: be careful NOT to enclose the word null in quotes or it will insert the string "null" instead.

Related

How to check if SQLite row is empty

I have the following which only inserts to column two if the value is empty:
UPDATE name
SET one=?,
two=COALESCE(two, ?),
three=?
WHERE id = ?
However, this only works if column two if the value is null. How can I get this to work if it is either NULL OR an empty string.
It should always insert to one and three. It should only insert to two if it is NULL or empty
I am using SQLite with PHP
If by "empty" you mean an empty string, you can use nullif():
two = COALESCE(NULLIF(two, ''), ?)
The more general solution is a CASE expression.
Don't store empty strings in TEXT columns.
Update the table to replace all empty strings with NULLs:
UPDATE name
SET two = NULL
WHERE TRIM(two) = ''
Now you can use your query, which is correct and in any other query you only need to check for NULL.

Form trouble: radio button ->yes,no or null

I'm sure I am missing something quite simple, but I have a form with a few yes/no inputs - type=radio. I have made the default NULL. YES is significant, NO is significant and NULL means user has never answered the question. When I UPDATE the db with user's selections, my NULL values are overwritten with 0 even though NO is not selected. I've read that if user doesn't choose either YES or NO that variable is NOT SET, therefore,
$licensedYN = (isset($_POST['licensed'])&&!empty($_POST['licensed']))?$_POST['licensed']:NULL;
$malpracticeYN = (isset($_POST['malpractice']))?$_POST['malpractice']:NULL;
$sqlAdd = $db->query("INSERT INTO temp (licensedYN,malpracticeYN) VALUES ('$licensedYN','$malpracticeYN')");
How do I get NULL to be inserted into DB and not '0'?
To allow NULL as a value in your licensedYN column... Run this query..
ALTER TABLE temp MODIFY licensedYN varchar(255) null;
This would allow you store null values in your db.
In your case you can just remove the quotes from the query and place it in the value as follows:
$licensedYN = (isset($_POST['licensed']) && !empty($_POST['licensed']))? "'{$_POST['licensed']}'" : 'NULL';
$malpracticeYN = (isset($_POST['malpractice'])) ? "'{$_POST['malpractice']}'": 'NULL';
$sqlAdd = $db->query("INSERT INTO temp (licensedYN,malpracticeYN) VALUES ($licensedYN,$malpracticeYN)");
In any case, you should consider working with prepared statements instead of concatenating strings. You will prevent many problems as sql injections, boost the query execution time and will not have headaches with quotation anymore...

postgresql insert null value on query

In my php code query, i got some error when i will place a null value
into the table. The column names "number1","number2", and "number3" are integers and can have a null value.
if there is no null value, the query works
query is like this
insert into table(number1,number2,number3) values (1,2,3);
but when I leave a blank value on the input form on the PHP,
for example I will not place value for column "number2", the query will look
like this.
insert into table(number1,number2,number3) values (1,,3);
it says ERROR: syntax error at or near ","
SQL state: 42601
Does anybody have an idea how to solve this?
this query is likely to be the solution but is there any other way?
insert into table(number1,number2,number3) values (1,null,3);
because i got so many variables like that and am a bit lazy to place some conditions like when that variable returns a blank value then value="null"
You insert NULL value by typing NULL:
INSERT INTO table(number1,number2,number3) VALUES (1,NULL,3);
If you have a variable and when that variable is empty you want to insert a NULL value you can use NULLIF with the variable enclosed in single quotes to prepare for that (this is somewhat dirty solution as you have to treat the variable as an empty string and then convert it to integer):
INSERT INTO table(number1,number2,number3) VALUES (1,NULLIF('$var','')::integer,3);

Enter either a date or a null value in database using MySql

I have searched the site and although I have found questions and answers similar I haven't been able to find an answer. After 4 hours of searching I've decided to bite the bullet and ask the question.
I have 4 date fields in a form that aren't required. I would like it to enter a date into the database if one of the fields has an entry or null if any are left blank.
I have an if statement that checks if the value is empty and if so $value = null, otherwise use $value = date("Y-m-d",strtotime($_post['value'])) to convert it to a date and this works well.
The problem is in my query. If I use '$value' it will insert the date correctly but won't insert a null value because using 'null' makes sql think it's a string. If I use just $value the null inserts just fine but the date goes in as 0000-00-00.
Any advice would be very much appreciated
Thanks for the advice so far...
Null is allowed, this is my script...
if(empty($_POST['fp32_original_install_date'])){
$fp32_install = NULL;
}else{
$fp32_install = date("Y-m-d",strtotime($_POST['fp32_original_install_date']));
}
$sql = "INSERT INTO accounts_cstm (id_c, support_c, install_date_c, sware_renewal_date_c, product_key_c, account_status_c, fp32_support_type_c, fp32_support_renewal_date_c, fp32_original_install_date_c) VALUES ('$Guid','$cdr_support', '$cdr_install', '$cdr_renew', '$prod_key', '$account_status', '$fp32_support', '$fp32_renew', $fp32_install)";
If I use in the query $fp32_install a null value goes in just fine but a date goes in as 0000-00-00, if I use '$fp32_install' the date goes in fine but a NULL value goes in as 1970-01-01 (probably because it sees 'NULL' as a string)
If I echo $fp32_install the value is shown as 2012-08-16 and the SQL type for the column is date and the default is NULL
If you are using posted values from a form, then $_POST['value'] will not be NULL.
You should check for empty values instead.
if($_POST['value']=="")
{
$value="NULL";
}
else
{
$value="'".date("Y-m-d",strtotime($_POST['value']))."'";
}
From the behavior you describe, it sounds as if your DATE column is defined with a DEFAULT 0 clause, or you are providing an invalid value.
According to the MySQL documentation:
<snip>
Invalid DATE, DATETIME, or TIMESTAMP values are converted to the “zero” value of the appropriate type ('0000-00-00' or '0000-00-00 00:00:00').
</snip>
It's difficult to diagnose the exact problem without seeing example code. As a starter, I suggest you try echoing out the SQL statement that is being sent to the database.
I have a strong suspicion that the value for the DATE column is going to appear with quotes around it, a string value of 'NULL', rather than the bare keyword NULL.

Insert NULL instead of empty string with PDO

I have a table which has some nullable fields and when the user enters nothing into the HTML form field, I want to insert NULL into that field, not an empty string (this is important as some of my SELECTs on these tables later use conditions such as WHERE x IS NOT NULL).
However, this version of bindParam code inserts an empty string into the nullable field instead of NULL.
$stmt2->bindParam(':title', $title, PDO::PARAM_STR);
I've been reading quite a bit and figured out that this is the answer to insert null into the field instead:
$stmt2->bindParam(':title', $title, PDO::PARAM_NULL);
But this means I need to pre-check all parameters that are being passed to nullable fields to determine if they are empty, and if so pass the PDO::PARAM_NULL instead of PDO::PARAM_STR. I can of course do this, but was hoping there might be a setting which would just tell PDO if it encounters an empty string, insert null instead.
I stumbled across this
$this->dbh->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_EMPTY_STRING);
But it has no effect and with further research I'm thinking this only affects record on the way out, not on the way in.
Any options other than pre-checking the variables?
If you want null, just insert null instead of empty string.
$stmt2->bindValue(':title', $title === '' ? null : $title, PDO::PARAM_STR);
Besides xdazz's more appropriate answer, you can often solve something like this in SQL: Just rephrase the query INSERT INTO ... VALUES (?) to something like INSERT INTO ... VALUES (NULLIF(?, '')).
This works really well. Another option is with
IF $val == null || $val == 'null' || $vall ==''
BindValue with PDO::PARAM_NULL
ELSE
BindValue with PDO::PARAM_STR

Categories