PDO 插入不起作用

PDO Insert does not work

我有一个问题,我无法通过 PDO 准备请求,每次它 returns 对我来说都是错误的。

   $table = 'paroles'; 
   $array = array(
        'timestamp' => 'VALEUR',
        'cle' => 'VALEUR',
        'titre' => 'VALEUR',
        'paroles' => 'VALEUR',
        'titre_trad' => 'VALEUR',
        'paroles_trad' => 'VALEUR'
    );
     
    $values = '';$datas = '';
    foreach ($array as $key => $value) {
        $values = $values.$key.',';
        $datas = $datas.':'.$key.',';
    }
    $values = trim($values, ',');
    $datas = trim($datas, ',');
     
    $requestconstr = 'INSERT INTO '.$table.'('.$values.') VALUES('.$datas.')';
     
    $sth = $this->_db->prepare($requestconstr);
     
    foreach ($array as $key => $value) {
        $sth->bindValue(':'.$key, $value);
    }
     
    if($sth->execute()){
        return true;
    }else return false;

    // PDOStatement Object ( [queryString] => INSERT INTO paroles(timestamp,cle,titre,paroles,titre_trad,paroles_trad) VALUES(:timestamp,:cle,:titre,:paroles,:titre_trad,:paroles_trad) )

看起来您正在正确构建查询,但无论如何,这可能是一种更简洁的方法,最后的检查应该会为您提供更多有关问题所在的信息:

$params = array_map(function($item) { return ":" . $item; }, array_keys($array));
$placeholders = implode(",", $params);
$columns = implode(",", array_keys($array));

$sql = "INSERT INTO {$table} ({$columns}) VALUES ({$placeholders})";

$bind = array_combine($params, array_values($array));
$sth = $this->_db->prepare($sql);
if ($sth->execute($bind)) {
    return true;
} else {
    die(print_r($this->_db->errorInfo(), true));
}