我正在尝试将所有随机生成的值(每个值都保存在不同的数组中)添加到同一个表中。
//Get the maximum nr of inputs, from the longest array.
$countMax = max(count($arrCA),count($arrZN),count($arrMP),count($arrEC),count($arrL),count($arrGP),count($arrNC),count($arrFS),count($arrNW))
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
//Add the values to the Database untill the maximum nr is reached.
for($i = 0; $i<$countMax; $i++) {
$query = "INSERT INTO Province
(CA,ZN,MP,EC,L,GP,NC,FS,NW)
VALUES('$arrCA[$i]','$arrZN[$i]','$arrMP[$i]',
'$arrEC[$i]','$arrL[$i]','$arrGP[$i]',
'$arrNC[$i]','$arrFS[$i]','$arrNW[$i]')";
$result = $conn->query($query);
if (!$result) die ("Database access failed: ".$conn->error);
}
现在的问题是我的 PHP 网页显示
Notice: Undefined offset: 13 on line 135;
任何有关如何改进此脚本的帮助将不胜感激!
最佳答案
根据我的意见,您应该在执行 $query
之前检查变量。
if(!isset($arrCA[$i])){
$arrCA[$i]="";
}
if(!isset($arrZN[$i])){
$arrCA[$i]="";
}
并使用isset
函数检查所有变量,然后将query
分配给$query
变量并执行query
$query = "INSERT INTO Province
(CA,ZN,MP,EC,L,GP,NC,FS,NW)
VALUES('$arrCA[$i]','$arrZN[$i]','$arrMP[$i]',
'$arrEC[$i]','$arrL[$i]','$arrGP[$i]',
'$arrNC[$i]','$arrFS[$i]','$arrNW[$i]')";
$result = $conn->query($query);
关于PHP 查询将多个随机长度数组写入 MySQL 数据库中的同一个表,而不会出现 "Undefined offset"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52833649/