I am trying to use the PDO bindValue but its not working on my side.
public static function insert($tableName, $columnValues = array()) {
$columns = array_keys ( $columnValues );
$columns = '`' . implode ( '`,`', $columns ) . '`';
$values = null;
$x = 1;
$y = 1;
foreach ( $columnValues as $value ) {
$values .= '?';
if ($x < count ( $columnValues )) {
$values .= ',';
}
$x ++;
}
$sql = "INSERT INTO {$tableName} ($columns) VALUES($values)" . '</br>';
if ($sqlString = DatabaseConnection::getConnectionInstance ()->pdo->prepare ( $sql )) {
foreach ( $columnValues as $value ) {
$sqlString->bindValue ( $y, $value );
$y ++;
}
if ($sqlString->execute ()) {
echo 'executed';
}
}
return false;
}
I have modified your function to use lazy binding see PDO info . NOTE your implode()
was not quite right. I have added echos to show results wich you should remove after testing.
public static function insert($tableName, $columnValues = array()) {
$columns = array_keys( $columnValues );
$params = array_values( $columnValues );// Array to hold values for lazy binding
$columns = '`' . implode ("`,`", $columns ) . '`';
$values = null;
$x = 1;/*
$y = 1;*/
foreach ( $columnValues as $value ) {
$values .= '?';
if ($x < count ( $columnValues )) {
$values .= ',';
}
$x ++;
}
$sql = "INSERT INTO {$tableName} ($columns) VALUES($values)" . '</br>';
if ($sqlString = DatabaseConnection::getConnectionInstance ()->pdo->prepare ( $sql )) {
echo $sql;//For Testing
echo "<br>";//For Testing
var_dump($params);//For Testing
if ($sqlString->execute ($params)) {
echo 'executed';
}
}
return false;
}
This function produces
INSERT INTO test (`Peter`,`Ben`,`Joe`) VALUES(?,?,?)
array(3) { [0]=> int(35) [1]=> int(37) [2]=> int(43) }
From
$columnValues = array("Peter"=>35, "Ben"=>37, "Joe"=>43);
$tableName ="test";
insert($tableName, $columnValues)
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.