简体   繁体   中英

php mysql pdo bindparam data not insert

When I Call this function , it shows no error, But Data not inserted. Database Connection is checked and its OK , Connection type PDO.

public function insert(){
    $table  = "category";
    $data   = array(
        'cat_id'    => 5, 
        'cat_name_en'   => 'Science', 
        'cat_info'  => 'All about nature', 
        'cat_tags'  => 'Physics, chemistry' 
        );
    $keys       = implode(', ', array_keys($data));
    $values     = ":".implode(", :", array_keys($data));
    echo $sql   = "INSERT INTO $table($keys) VALUES($values)";
    $stmt       = $this->db->prepare($sql);
    foreach ($data as $key => $value) {
        $stmt->bindParam(':'.$key, $value);
    }
    return $stmt->execute();

}

Database connection is ok. Because it works on SELECT and DELETE query, But not working INSERT and UPDATE query. I do not want alternative but i want where is my bug. Please help me. I am trying to solve it for 2 days.

Windows 10 64bit
WampServer 3.0.8
PHP 7.1
MySQL 5.7

You need to bindValue() instead of bindParam() . Change you foreach loop to

foreach ($data as $key => $value) {
        $stmt->bindValue(':'.$key, $value);
    }

See the doc:

http://php.net/manual/en/pdostatement.bindvalue.php

See the difference here: What is the difference between bindParam and bindValue?

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