I have a CodeIgniter based web application that was previously using a MySQL database. I changed the database.php to connect it to SQL Server after migrating all the data/tables. I'm testing the application now and login worked. However, when adding an object from a form in the web app, it throws an error on insert query.
The error mentions that it cannot insert to guests
table when ID Insert property is on.
A Database Error Occurred
Error Number: 23000/544
[Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Cannot insert explicit value for identity column in table 'guests' when IDENTITY_INSERT is set to OFF.
INSERT INTO "guests" ("id", "firstname", "lastname", "gender", "dob",
"email", "country_id", "state_id", "city_id", "address", "mobile",
"id_type", "id_no", "remark", "vip", "password", "added") VALUES (0,
'abc', '123', '1', '', 'abc123@123.com', '', '', '', '', '899834534',
'', '', '', 0, '6367c48dd193d56ea7b0baad25b19455e529f5ee', '2019-01-21
09:58:11')
Filename: C:/wamp64/www/hms/system/database/DB_driver.php Line Number: 691
I know the workaround is T-SQL SET IDENTITY_INSERT guests ON
but why are these insert queries structured this way at all?
I checked DB_Driver.php and here's perhaps the relevant portion
/**
* Generate an insert string
*
* @param string the table upon which the query will be performed
* @param array an associative array data of key/values
* @return string
*/
public function insert_string($table, $data)
{
$fields = $values = array();
foreach ($data as $key => $val)
{
$fields[] = $this->escape_identifiers($key);
$values[] = $this->escape($val);
}
return $this->_insert($this->protect_identifiers($table, TRUE, NULL, FALSE), $fields, $values);
}
// --------------------------------------------------------------------
/**
* Insert statement
*
* Generates a platform-specific insert string from the supplied data
*
* @param string the table name
* @param array the insert keys
* @param array the insert values
* @return string
*/
protected function _insert($table, $keys, $values)
{
return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
}
How can I make changes to the project so that it does not try to insert the Identity column in every insert query?
Edit: The above code excerpt is likely not the place where query is formed because I changed it and the error remains.