Klapsius
Klapsius

Reputation: 3359

PHP value null into sql server insert statement

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,

Upvotes: 2

Views: 661

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157880

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.

Upvotes: 4

Related Questions