我有以下代码可以正常工作,因为它使用 pdo 即使是动态生成 sql 查询(我认为)。
$fields = array(
'col1' => 'radiobutton1',
'col2' => 'radiobutton2'
);
$parts = array();
foreach($fields as $dbfield => $field){
$parts[] = '`' . $dbfield . '` = :' . $dbfield;
}
$DBH = new PDO( "mysql:host=localhost;dbname=database", "user", "pass" );
$DBH -> setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$STH = $DBH -> prepare( 'UPDATE `table1` SET ' . join(', ', $parts) . ' WHERE `id`= :id' );
$STH -> bindParam( ':id', $some_id_here, PDO::PARAM_INT, 4 );
foreach($fields as $dbfield => $field) {
$value = isset($_POST[$field]) ? 1 : 0;
$STH -> bindValue( ':' . $dbfield, $value, PDO::PARAM_INT);
}
$STH -> execute();
我的问题是,我该如何更改它以便执行 sql 插入而不是更新?