我正在尝试使用PDO预处理语句将Excel文件中的数据插入Access 2007数据库。代码试图做的是检查Excel工作表中的值是否存在于数据库中,如果不存在则添加但不执行任何操作
以下是代码:
$conn = connect_to_impact();
//******************************************
//select statement
$select = 'SELECT < ? FROM < ?';
$select_query = $conn->prepare($select);
for ($h = 2; $h<count($clmn[0]); $h++){
$value = $clmn[0][$h];
// query execution
$select_query->execute(array($clmn[0][1], $clmn[0][1]));
$impact_no_result = $select_query->fetchAll();
//query result in multidimensional array
$impact_no_arr = impact_no_select($impact_no_result);
// create an indexed array of results
$impact_no_r = impact_no_indexed($impact_no_arr, $clmn[0][1]);
if(is_null($impact_no_r)){
$insert_impact_no = 'INSERT INTO < ? (< ?) VALUES (< ?)';
$simple_arr = [$clmn[0][1], $clmn[0][1], $value];
$insert_query = $conn->prepare($insert_impact_no);
$insert_query->execute($simple_arr);
}
// then if the value in the column is not in the indexed array insert it
elseif(!in_array($value, $impact_no_r)){
$insert_impact_no = 'INSERT INTO < ? (< ?) VALUES (< ?)';
$simple_arr = [$clmn[0][1], $clmn[0][1], $value];
$insert_query = $conn->prepare($insert_impact_no);
$insert_query->execute($simple_arr);
}
}
答案 0 :(得分:0)
实际上,替换不能用于PDO预处理语句中的表名和列名。这是解决问题的代码
$conn = connect_to_impact();
//******************************************
//select statement
$select = "SELECT ". $clmn[0][1] . " FROM " . $clmn[0][1];
//repeat for each row the the excel sheet starting from row 2
for ($h = 2; $h<count($clmn[0]); $h++){
//take each value from each row from column A
$value = $clmn[0][$h];
// query execution
$impact_no_result = $conn->query($select);
if($impact_no_result){
$impact_no_result_ass = $impact_no_result->fetchAll();
}
//if there is no result in the select query
if($impact_no_result == false){
$insert_impact_no = "INSERT INTO ". $clmn[0][1] . "(" . $clmn[0][1] . ") " . "VALUES ('" . $value . "');";
$execute = $conn->query($insert_impact_no);
}
//if there is a result in the select query
else {
//put query result in array
$impact_no_arr = impact_no_select($impact_no_result_ass);
//if value is not in array insert it
if(!in_array($value, $impact_no_arr)){
$insert_impact_no = "INSERT INTO ". $clmn[0][1] . "(" . $clmn[0][1] . ") " . "VALUES ('" . $value . "');";
$execute = $conn->query($insert_impact_no);
}
}
}