简体   繁体   中英

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.

尝试

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

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM