0

I have a form that POST value keeps coming as "" empty string into a unique SQL field. It has to be unique as the field is optional but jet it can not have 2 same values. The unique value does allow null multiple values. I don't even want to say what I tried to do, I'm trying to fix this for last few days. Closest that I got is putting '$OIB'=IF('$OIB'='',NULL,'$OIB' into NSERT INTO statement, then i get null values into a database but for some reason when the number is entered into OIB form field it puts number 1 into a database...

$result = mysqli_query($conn, "SELECT OIB, NAZIV FROM STRANKEP WHERE OIB = '$OIB' OR NAZIV = '$NAZIV'");

if(mysqli_num_rows($result) == 0) {
     // row not found, do stuff...
     $sql = "INSERT INTO STRANKEP (NAZIV, OIB, EMAIL, ADRESA, TELEFON) VALUES ('$NAZIV', CASE WHEN '$OIB' = '' THEN 'NULL', '$EMAIL', '$ADRESA', '$TELEFON')";
    $query = mysqli_query($conn, $sql);

This solution gets me null but not the real $OIB when entered into form, it just puts number 1.

$result = mysqli_query($conn, "SELECT OIB, NAZIV FROM STRANKEP WHERE OIB = '$OIB' OR NAZIV = '$NAZIV'");

if(mysqli_num_rows($result) == 0) {
     // row not found, do stuff...
     $sql = "INSERT INTO STRANKEP (NAZIV, OIB, EMAIL, ADRESA, TELEFON) VALUES ('$NAZIV', '$OIB'=IF('$OIB'='',NULL,'$OIB'), '$EMAIL', '$ADRESA', '$TELEFON')";
    $query = mysqli_query($conn, $sql);

Thank you in advance for the help.

ikiK
  • 5,467
  • 3
  • 11
  • 27

3 Answers3

2

Try

CASE '$OIB' WHEN '' THEN NULL ELSE '$OIB' END
Ted Hopp
  • 222,293
  • 47
  • 371
  • 489
2

You can use also IF Clause

Like so

INSERT INTO STRANKEP (NAZIV, OIB, EMAIL, ADRESA, TELEFON) VALUES 
('$NAZIV', IF('$OIB' = '', NULL,'$OIB'), '$EMAIL', '$ADRESA', '$TELEFON');

But as mentioned in my comment use prepared statements like in PDO https://phpdelusions.net/pdo#prepared

nbk
  • 20,484
  • 4
  • 19
  • 35
1

I would recommend nullif(). It is a built-in standard function to do exactly this:

nullif(?, '')

Note: Do not munge queries with constant values. That makes the code subject to SQL injection attacks. And it can introduce very hard-to-debug errors. Use parameters!

Gordon Linoff
  • 1,122,135
  • 50
  • 484
  • 624