当我运行下面的脚本时,我在 php 中出现"undefined offset 2"错误


if (isset($_POST['sub']))
{
    $grpm_phno = $_POST['grpm_phno'];
    $grmid = $_POST['groupid'];
    $grpm_name = $_POST['grpm_name'];
    $name = explode(',', "$grpm_name");
    $phone = explode(',', "$grpm_phno");
    $countt = count($name);
    for ($i = 0; $i <= $countt; $i++)
    {
        $x = $name[$i];
        $y = $phone[$i];
        $dt = date('Y-m-d h:i:s');
        // Insert Query of SQL
        $query = mysql_query("insert into grp_mst(grpm_name, grpm_phno, grpm_grpcatm_id,grpm_typ,grpm_crtdon) values ('$x', '$y', '$grmid', 'b', '$dt')");
    }
}

输入给定:

name:raj,mohan
number:61231,3618372

输出:

raj :61231
mohan:3618372

和空行任何帮助

为什么不使用 foreach(),因为它要照顾索引本身): -

foreach($name as $key=>$value){
 $x = $value;
 $y = $phone[$key];
 $dt = date('Y-m-d h:i:s');
 $query = mysql_query("insert into grp_mst(grpm_name, grpm_phno, grpm_grpcatm_id,grpm_typ,grpm_crtdon) values ('$x', '$y', '$grmid', 'b', '$dt')");
}

重要说明: -

1。mysql_*库在PHP-5.5中弃用,并在PHP-7中删除。将最新的php 7版本转向mysqli_*PDO

2.总是使用mysqli_*prepared statementsPDO库来防止SQL INJECTION的代码。

参考: -

php mysqli准备

PHP PDO准备

您的数组中有2个项目,索引 2是第三个(并且在给定输入的情况下不存在)

$countt = count($name);
for ($i = 0; $i <= $countt; $i++)
/* => */
for ($i = 0; $i < $countt; $i++)
$name = explode(',', "$grpm_name");
$phone = explode(',', "$grpm_phno");

将其重写为

$name = explode(',', $grpm_name);
$phone = explode(',', $grpm_phno);

使用foreach循环或修改for循环:

for ($i = 0; $i < $countt; $i++)

最新更新