以前,我是雄辩地将数据从csv插入数据库。但是,我觉得这很慢,因此我尝试在Laravel中使用Raw Query进行测试,如下所示:
$query = Committee::where('name', $committee_arr['name']);
if ($committee_arr['mailing_address_city']) {
$query->where('mailing_address_city', $committee_arr['mailing_address_city']);
}
if ($committee_arr['mailing_address_state']) {
$query->where('mailing_address_state', $committee_arr['mailing_address_state']);
}
if ($committee_arr['mailing_address_zip']) {
$query->where('mailing_address_zip', $committee_arr['mailing_address_zip']);
}
$committee = $query->first();
if ($committee) {
$committee_arr['updated_at'] = date('Y-m-d H:i:s');
$committee_arr['updated_by'] = $this->data['user_id'];
try {
$valueSets = array();
foreach ($committee_arr as $k => $v) {
$valueSets[] = $k . " = '" . $v . "'";
}
DB::update("Update `fec` set " . implode(", ", $valueSets) . " where id = " . $committee->id);
$committee_id = $committee->id;
} catch (\Exception $e) {
$error_encountered = true;
$this->error_arr[] = $e->getMessage();
$this->error_row_numbers[] = $this->data['row_value'];
}
} else {
$committee_arr['created_at'] = date('Y-m-d H:i:s');
$committee_arr['created_by'] = $this->data['user_id'];
try {
$columns = implode(", ", array_keys($committee_arr));
$values = "'" . implode("', '", array_values($committee_arr)) . "'";
DB::insert("INSERT INTO `fec`($columns) VALUES ($values)");
$committee_id = DB::getPdo()->lastInsertId();
} catch (\Exception $e) {
$error_encountered = true;
$this->error_arr[] = $e->getMessage();
$this->error_row_numbers[] = $this->data['row_value'];
DB::rollback();
}
}
但是,在此过程中,我遇到了这些单引号的问题。我不知道如何在Laravel中使用mysqli_real_escape_string
。我也注意到了addslashes
,但我不认为这是理想的方法。
那么,有什么办法可以解决这个问题?此外,如果您有任何插入参数绑定之类的想法,欢迎您。
如果您想知道$committee_arr
包含的内容,则如下所示:
Array
(
[name] => O'KANE, PATRICK M
[mailing_address_city] => SAN ANTONIO
[mailing_address_state] => TX
[mailing_address_zip] => 782583940
[employer] => ENERGY TRANSFER EMPLEE MGMT CO
[occupation] => SR DIRECTOR - PL HEDGNG/COMMOD
)
我主要关心的是正确处理O'Kane
。但是,如果我必须确切地说出来,那么我想用下面的方法来处理。但是,问题在于,这些领域和价值是完全动态的。它将如上所示排列在数组中。不限于六个以上的字段和值,可能还有更多。
$results = DB::select( DB::raw("SELECT * FROM some_table WHERE some_col = :somevariable"), array(
'somevariable' => $someVariable,
));
答案 0 :(得分:0)
尝试如下所示的关联数组的addslashes()函数。
$committee_arr=array_map('addslashes', $committee_arr);
print_r($committee_arr);
您将获得如下所示的数组。
Array
(
[name] => O\'KANE, PATRICK M
[mailing_address_city] => SAN ANTONIO
[mailing_address_state] => TX
[mailing_address_zip] => 782583940
[employer] => ENERGY TRANSFER EMPLEE MGMT CO
[occupation] => SR DIRECTOR - PL HEDGNG/COMMOD
)