3

My page sends using ajax data to a php script. one of the vars that the script gets is: $product_disc now a small test that I have done inside the script clearly revealed that $product_disc is null. the test:

if ($product_disc == null)
 {$test="null";}
 else {$test="not null";}

I make my code return $test to the ajax calling procedure:

$return_array['success'] = array ('test' => $test);

And using Firebug I see that the ajax response has: "test":"null"
So i conclude that $product_disc is of value: null

Now, inside my script I'm using the following code to insert data to MySql DB:

$stmt = mysqli_prepare($link, "INSERT INTO set_products (id,discount) VALUES (NULL , ?)");
mysqli_stmt_bind_param($stmt, "i", $product_disc);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);

The query is being executed, but the value that was inserted is 0 and not NULL!
Only when I explicitly added: $product_disc=null; before the MySqli statements, the value that was inserted was NULL.

Why is that? What's the different between a null and a null? I followed this answer in stackoverflow hoping that i could easily insert NULLs but then came this problem...

Thank you!

PS @stackoverflow team - Your spell checking dictionary doesn't recognize the word stackoverflow!

Community
  • 1
  • 1
Israel
  • 1,184
  • 2
  • 13
  • 26

1 Answers1

4

You prepare product_disc as integer, null is not an integer. It is converted to 0.

While preparing as a string, would definitely fix your issue, it defeats the purpose of preparing a mysql statement. Consider this solution:

mysqli_stmt_bind_param($stmt, $product_disc==null?'s':'i', $product_disc);
Khez
  • 10,172
  • 2
  • 31
  • 51
  • Thank you Khez, i'll use your suggestion, but do you know why when i explicitly declared the var as NULL it behaved differently? in both ways the var was a null, but one way it was converted to integer and the other way it wasn't – Israel Apr 15 '11 at 13:44
  • Like I asked in your OP, can you supply the code? I'm sure there's a practical reason – Khez Apr 15 '11 at 13:45