简体   繁体   中英

PHP insert mysql NULL in empty array value for PDO insert

I have a pdo function that uses an array to add values to a table. It adds perfectly, my issue is that if an array value is empty that it must add it as NULL value, and not as a blank field in the database. I have an array, which I am using to create a mysql query. eg of array

$arr = [
    'table' => [
        'fields' => [
            'id',
            'keyname',
            'lang',
            'value'
        ],
        'values' => [
            '',
            'some key name',
            'some lang',
            'some value'
        ]
    ]
];

I have tried the following (just a basic example)

foreach($array as $a => $v) {

   foreach($v as $p => $r){

      foreach($r as $f){

         $val = NULL;
         $f = trim($f);     

         if (empty($f)) {   
           $stmt->bindParam($f, $val, PDO::PARAM_NULL);             
           echo "empty <br/>";
        }

      }

   }

}

The above does return true for all the empty values in the array, however when I run the method to insert the values into the database they show blank fields and not NULL . I also tried the array_map function which did not work at all.

Here is the whole function I am writing:

public function add($array) {

        $result = true;

        foreach($array as $a => $v) {

            // the pdoquery prepares the statement to work as mysql query
            $sql = $this->pdoquery($a, $v);

            $query = "INSERT INTO " . $sql;

            $stmt = $this->db->prepare($query);

            ////this is where I am adding the foreach loops

            $exec = $stmt->execute();

            if(!$exec) $result = false;
        }
        if($result) {
            $id = $this->db->lastInsertId();
            return $id;
        }
        else return false;


    }

Just provide NULL instead of empty string '' when you insert in the DB like so:

$arr = [
    'table' => [
        'fields' => [
            'id',
            'keyname',
            'lang',
            'value'
        ],
        'values' => [
            null,
            'some key name',
            'some lang',
            'some value'
        ]
    ]
];

Then it will leave it null instead of empty string.

Also please note that your field structure in DB must allow it to be able to be NULL otherwise it will return error that field cannot be null

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