3

How I can tell PDO to insert NULL instead of an empty value ?

Example :

        $SQL = 'INSERT INTO `Calendars_Events` (`CalendarID`, `AccID`, `DateFrom`, `DateTo`, `Location`, `Title`, `Description`)
                VALUES (:CalendarID, :AccID, :From, :To, :Location, :Title, :Description)';

        $Query = $this->DB->Link->prepare($SQL);
        $Query->bindParam(':CalendarID',        $CalendarID,        PDO::PARAM_INT);
        $Query->bindParam(':AccID',             $this->Account->ID, PDO::PARAM_INT);
        $Query->bindParam(':From',              $From,              PDO::PARAM_INT);
        $Query->bindParam(':To',                $To,                PDO::PARAM_INT);
        $Query->bindParam(':Location',          $Location,          PDO::PARAM_STR);
        $Query->bindParam(':Title',             $Title,             PDO::PARAM_STR);
        $Query->bindParam(':Description',       $Description,       PDO::PARAM_STR);
        $Query->execute();

If Location is empty, it will insert nothing (empty, so '') instead of NULL.

Thanks

1 Answer 1

8

Pass in null instead of the empty $Location string, in case the string is empty:

empty($Location) ? null : $Location;
Sign up to request clarification or add additional context in comments.

3 Comments

Ok, hmm so I have to tell php first that the value is null instead of empty ? I tought MySQL / PDO was doing that on INSERT
@DavidBélanger, well, if you pass it an empty string, it has no way of knowing that you actually want a NULL instead of an empty string... An empty string is a perfectly reasonable value, so it doesn't replace that with NULL on its own.
That is true... it is perfectly legit ! Thanks a lot, of corse, it is working !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.