问题
I am working with codeigniter / SQL. Where I want to insert unicode string with 'N' Prefix the insert. How can I achieve it in regular insert.
Regular Code:
$data = array(
'title' => 'My title' ,
'name' => 'My Name' ,
'data' => 'My data'
);
$this->db->insert('mytable', $data);
INSERT Trying to Achieve:
INSERT INTO mytable (title, name, data)
VALUES ('My title','My Name',N'My data');
Is there any way to achive the above insert instead of manually writing the Query.?
回答1:
This is the simplest way to do it.
$data = array(
'title' => 'My title' ,
'name' => 'My Name' ,
'data' => 'N'.'My data'
);
$this->db->insert('mytable', $data);
Or, if the prefix needs to more dynamic do this
$pre = foo(bar);
$data = array(
'title' => 'My title' ,
'name' => 'My Name' ,
'data' => $pre.'My data'
);
$this->db->insert('mytable', $data);
回答2:
I was having problems with Unicode using Codeignter 3, driver sqlsrv and I managed to get it working modifying the System/database/DB_Driver.php. Probably there is a better solution out there, it's not beautiful but it's working, just modify the functions _insert and _update.
protected function _insert($table, $keys, $values)
{
foreach($values as $key => $value)
{
if(substr($value,0,1) == "'")
{
$values[$key] = "N". $value;
}
}
return 'INSERT INTO '.$table.' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')';
}
protected function _update($table, $values)
{
foreach($values as $key => $value)
{
if(substr($value,0,1) == "'")
{
$values[$key] = "N". $value;
}
}
foreach ($values as $key => $val)
{
$valstr[] = $key.' = '.$val;
}
return 'UPDATE '.$table.' SET '.implode(', ', $valstr)
.$this->_compile_wh('qb_where')
.$this->_compile_order_by()
.($this->qb_limit ? ' LIMIT '.$this->qb_limit : '');
}
来源:https://stackoverflow.com/questions/33198127/codeigniter-add-n-in-sql-query-insert-unicode-text