ikiK
ikiK

Reputation: 6532

Converting empty string into null

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.

Upvotes: 1

Views: 1543

Answers (3)

Gordon Linoff
Gordon Linoff

Reputation: 1269683

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!

Upvotes: 2

Ted Hopp
Ted Hopp

Reputation: 234795

Try

CASE '$OIB' WHEN '' THEN NULL ELSE '$OIB' END

Upvotes: 3

nbk
nbk

Reputation: 49375

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

Upvotes: 2

Related Questions