I have created a function to insert data into the MySQL database.
// Inserting in the database
public function addData($table, array $columns, array $values) {
// Defining columns
$each_column = null;
foreach ($columns as $column) {
$each_column .= '`' . $column . '`, ';
}
$column_sentence = substr($each_column, 0, -2);
// Defining values
$each_value = null;
foreach ($values as $value) {
$each_value .= ':' . $value . ', ';
}
$value_sentence = substr($each_value, 0, -2);
// Go ahead with prepared SQL
$sql = "INSERT INTO `$table` ($column_sentence) VALUES ($value_sentence)";
$statement = $this->pdo->prepare($sql);
foreach (array_combine($columns, $values) as $column => $value) {
$statement->bindValue(':' . $column, $value);
}
// Execute that baby
$statement->execute();
$statement->errorCode();
$statement->errorInfo();
}
This is how I run this function:
$db->addData('test', array('id', 'ip', 'name'), array(24, 123456789, 'Reza'));
My problem is that I get this warning:
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
What exactly is wrong with that function?