foreach($parentinfojson as $value) {
if (!empty($parentinfojson )) {
$stmt2 = $dbh -> prepare("INSERT INTO parentinfo (last_name,first_name,status) VALUES (:lastname,:firstname,:status)");
$stmt2_ = $stmt2 -> execute(array(':firstname' => $value['firstname'], ':lastname' => $value['lastname'], ':status' => $status));
} else {
$stmt2_ = $stmt2 -> execute();
}
}
if ($stmt2_ && $stmt3_ && $stmt1_ && $stmt_ && $stmt5_ && $stmt4_) {
echo json_encode(array(
'error' => false,
'message' => "Added"
));
}
这是我在表格中的Inserting
新数据中执行的。当我测试添加空数据(parentinfojson
为空)时,我得到Notice: Undefined variable: stmt2_
的错误。我做的是我添加了一个else
语句,我初始化变量仍然我得到错误。我试图在else语句中回应一些东西,但我得到错误。现在,当json
为空时,我对如何初始化变量没有想法,因此我没有收到错误undefined variable
答案 0 :(得分:1)
你刚刚在循环中定义了$stmt2
,如果$parentinfojson
为空,它肯定会被定义为未定义。为什么不定义/初始化它。
// initialize up top
$stmt_ = $stmt1_ = $stmt2_ = $stmt3_ = $stmt4_ = $stmt5_ = false;
$stmt2 = $dbh->prepare("INSERT INTO parentinfo (last_name,first_name,status) VALUES (:lastname,:firstname,:status)");
foreach($parentinfojson as $value) {
$stmt2_ = $stmt2->execute(array(
':firstname' => $value['firstname'],
':lastname' => $value['lastname'],
':status' => $status
));
}
if ($stmt2_ && $stmt3_ && $stmt1_ && $stmt_ && $stmt5_ && $stmt4_) {
echo json_encode(array(
'error' => false,
'message' => "Added"
));
}
旁注:另一种方法是动态构建查询,包括占位符和值。因此,您不必循环每批插入,而是创建SQL批处理插入,然后将所有值绑定到一个插入调用中:
$stmt_ = $stmt1_ = $stmt2_ = $stmt3_ = $stmt4_ = $stmt5_ = false;
if(!empty($parentinfojson)) {
$base_query = 'INSERT INTO parentinfo (last_name, first_name, status) VALUES ';
$placeholders = implode(',', array_map(function($batch){
return '(' . implode(',', array_fill(0, count($batch), '?')) . ')';
}, $parentinfojson));
$base_query .= $placeholders;
$parentinfojson = call_user_func_array('array_merge', array_map('array_values', $parentinfojson));
$stmt2 = $dbh->prepare($base_query);
$stmt2_-> $stmt2->execute($parentinfojson);
}
答案 1 :(得分:0)
您接收的json变量可能不是空的,所以您还应该添加一个检查有效的json,这是检查有效json的函数
function isJson($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}