PHP 查询将多个随机长度数组写入 MySQL 数据库中的同一个表,而不会出现 "Undefined offset"错误

标签 php mysql

我正在尝试将所有随机生成的值(每个值都保存在不同的数组中)添加到同一个表中。

//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/

相关文章:

javascript - php将html输入保存到数据库

php - 服务器 :run Exception There are no commands defined in the "server" namespace

javascript - ajax请求和PHP函数后刷新页面

mysql - 在 MySQL 中连接表并聚合数据?

mysql - 立即从表 AND 'archive' 表中选择

php - Laravel 护照 : auth:api behaving like auth:web

php - mysql转换问题。警告:mysqli_fetch_all()期望参数1为mysqli_result,在中给出 bool 值

mysql - 不允许我设置任何端口的监听器 (Oracle Netca)

Mysql 替换正则表达式

python - 如何在Django中使用LIKE语句执行mysql查询