php mysql pdo bindparam data not insert

826 views Asked by At

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

1

There are 1 answers

2
B. Desai On BEST ANSWER

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?