我想使用预处理语句向表中插入多行。为此,我使用循环从数组中提取数据并将其用于y语句参数,这是我的代码示例:
require_once("connect.php");
$data_array = Array();
$string = 'faycal,18,12,2016,podes|Arab,19,12,2016,kashi|faycal,20,12,2016,exec';
function create_array($input){
$formated_array = explode('|', $input);
$query = $con->prepare("INSERT INTO my_table (bill_name,bill_num,month,year,type) VALUES(?, ?, ?, ?, ?)");
for ($i = 0;$i < count($formated_array);$i++){
for($j = 0;$j < 5;$j++){
$data_array[$i][$j] = explode(',', $formated_array[$i])[$j];
}
$query->bind_param($name, $num, $month, $year, $type);
$name = $data_array[$i][0];
$num = (int)$data_array[$i][1];
$month = (int)$data_array[$i][2];
$year = (int)$data_array[$i][3];
$type = $data_array[$i][4];
$query->execute();
}
echo "Records have been saved successfully";
}
create_array($string);
我在没有执行语句的情况下测试了这个函数并试图回显data_array,一切都运行得很好所以我假设我的SQL语句出了问题我无法理解进行。
答案 0 :(得分:1)
SCOPE,范围,范围默认情况下,$con
变量在函数内部不可见。 SO将其作为参数传递给函数
require_once("connect.php");
$data_array = Array();
$string = 'faycal,18,12,2016,podes|Arab,19,12,2016,kashi|faycal,20,12,2016,exec';
function create_array($con, $input){
$formated_array = explode('|', $input);
$query = $con->prepare("INSERT INTO my_table (bill_name,bill_num,month,year,type) VALUES(?, ?, ?, ?, ?)");
for ($i = 0;$i < count($formated_array);$i++){
for($j = 0;$j < 5;$j++){
$data_array[$i][$j] = explode(',', $formated_array[$i])[$j];
}
$query->bind_param($name, $num, $month, $year, $type);
$name = $data_array[$i][0];
$num = (int)$data_array[$i][1];
$month = (int)$data_array[$i][2];
$year = (int)$data_array[$i][3];
$type = $data_array[$i][4];
$query->execute();
}
echo "Records have been saved successfully";
}
create_array($con, $string);