2

I would like to insert value NULL in to sql server table.

$value = $_POST['value'];

then PDO with (INSERT .... :value.....)

and execute(array(':value' => "$value")); but when html input field is empty I got empty field on sql but I would like to see NULL I tried with

if ($_POST['value'] ==''){$value = NULL;}else{....}

but nothing happens.

My sql table looks like:

[field] [varchar](20)  NULL,
3
  • 2
    You shouldn't need quotes around $value in the execute statement. Can you remove those and try again? Aug 27, 2015 at 15:29
  • field must accept null value and it must be without default value... then insert a new record without give the field any value .. it will take null automatically Aug 27, 2015 at 15:31
  • hot to change that on management studio?
    – Klapsius
    Aug 27, 2015 at 15:33

1 Answer 1

4

Regarding NULL values in prepared statements in general: ANY NULL value that was actually bound into statement, is always being sent to database as NULL. No exceptions.

Example:

$stmt = $db->prepare("SELECT isnull(?)");
$stmt->execute(array(NULL));
var_dump($stmt->fetchColumn());
// string(1) "1"

Regarding your particular code, as it was pointed out in the comments, your problem is caused by wrong syntax. In PHP, variables have to be addressed without quotes. Quotes are used in PHP to delimit strings. While variables, again, have to be addressed without quotes.

1
  • 1
    Except he's cast it to a string : ':value' => "$value"
    – CD001
    Aug 27, 2015 at 15:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.