This is my code. I believe it does not bind the value's to the parameters.. But I don't know why:
public function create($fields)
{
$keys = array_keys($fields);
$values = null;
$x = 1;
foreach($fields as $field) {
$values .= '?';
if ($x < count($fields)) {
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO users (`" . implode('`, `', $keys) . "`) VALUES ({$values})";
if(!$this->db->prepare($sql)->execute($fields)) {
return true;
}
return false;
}
And on index.php:
$user = new User();
$user->create(array(
'name' => 'test',
'username' => 'test2',
'email' => 'test@gmail.com'
));
Why are my values not bound to the parameters? This is the full error:
An exception occurred while executing 'INSERT INTO users (
name
,username
,SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
If you're using the ?
way for your query, the array that you send in params might not have keys i think!
EDIT: do execute(array_values($fields))
, you must use the keys when there are params like username = :username, pass = :pass
etc
public function create($fields) { $keys =''; $values = ''; foreach($fields as $k=>$field) { $keys[] = $k; $values[] = $field; } $sql = "INSERT INTO users (".implode(',',$keys).") VALUES ("'".implode ("','",$values)."'")"; if(!$this->db->prepare($sql)->execute($fields)) { return true; } return false; }
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.