1

I want to insert NULL Value in Database

$managerId = $_POST['managerId'];

if($managerId == 0)
{
    $managerId = NULL;
}
else
{
    $managerId = 14;
}
$mysql_user_resultset = mysqli_query($con, "INSERT into user (managerId) VALUES ('$managerId')");

I am using like this. Its not working, Value doesn't insert.

How to insert both Null value and some value in Same variable..

Its Because of '$managerId' - single quotation.

How to define for both the types

Mohaideen
  • 303
  • 1
  • 5
  • 17

3 Answers3

2

PHP concatenates the null value as an empty string. So, to get it work, try this :

if($managerId == 0)
{
    $managerIdInQuery = 'NULL';
}
else
{
    $managerIdInQuery = 14;
}
$mysql_user_resultset = mysqli_query($con, "INSERT into user (managerId) VALUES ($managerIdInQuery)");
Sebastien C.
  • 4,649
  • 1
  • 21
  • 32
1

When you concatenate the $managerId variable, you are getting this query string:

"INSERT into user (managerId) VALUES ('')"

So, you are trying to insert an empty string. This is not what you want. The easiest way is to remove the quotes, like

"INSERT into user (managerId) VALUES ($managerId)"

This will work if your managerId field can be null, and still be valid for integer values.

Aioros
  • 4,373
  • 1
  • 18
  • 21
0
  1. Set the columns default value to NULL
  2. Try this line:

    $managerId = (int) $managerId; // Convert to INT to avoid SQL injection $mysql_user_resultset = mysqli_query($con, "INSERT into user (managerId) VALUES (".($managerId?$managerId:'DEFAULT').")");

If $managerId is set, $managerId will be inserted, elsewise the default value NULL.

André
  • 477
  • 3
  • 11