I'm trying to update my PHP code by binding parameters with PDOStatement::bindValue.
The code is receiving an array with key-value pairs with the same names (keys) as fields in MySQL-database.
Table is like
CREATE TABLE `kund` (
`kund_nummer` smallint(6) NOT NULL AUTO_INCREMENT,
`fornamn` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL,
`efternamn` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL,
`telefon` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL,
`org_nummer` char(10) COLLATE utf8_unicode_ci DEFAULT NULL,
`utflyttdatum` date DEFAULT NULL,
`kommentar` varchar(75) COLLATE utf8_unicode_ci DEFAULT NULL,
`sparad_datum` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`kund_nummer`),
UNIQUE KEY `efternamn` (`efternamn`,`org_nummer`)
) ENGINE=MyISAM
AUTO_INCREMENT=69
DEFAULT CHARSET=utf8
COLLATE=utf8_unicode_ci |
And the PHP code is: ... $fields = $_POST; ...
$query = "INSERT INTO kund (";
foreach ($fields as $k => $v) {
$query .= $k . ",";
}
$query = substr($query, 0, -1);
$query .= ") VALUES (";
foreach ($fields as $k => $v) {
$query .= ":$k,";
}
$query = substr($query, 0, -1);
$query .= ")";
$stmt = $conn->prepare($query);
foreach ($fields as $k => $v){
$stmt->bindValue("':$k'",$v,PDO::PARAM_STR);
}
try {
$stmt->execute();
} catch (PDOException $ex) {
if ($ex->getCode() == 23000) {
}
echo $ex;
}
I get the error:
exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: parameter was not defined'
Can some one tell what's wrong? Greetings.