当我运行下面的脚本时,我在php中得到一个“未定义的偏移2”错误

时间:2017-12-15 06:41:10

标签: php

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

和空行 任何帮助

4 个答案:

答案 0 :(得分:3)

为什么不使用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中删除。转向mysqli_*PDO以及最新的php 7版本。

2.始终使用prepared statementsmysqli_*库中的PDO来阻止您的代码来自SQL INJECTION

<强> 参考: -

php mysqli prepare

php PDO prepare

答案 1 :(得分:1)

您的数组中有2个项目,索引2是第三个项目(并且根据您的输入不存在)

$countt = count($name);
for ($i = 0; $i <= $countt; $i++)
/* => */
for ($i = 0; $i < $countt; $i++)

答案 2 :(得分:0)

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

将其重写为

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

答案 3 :(得分:0)

使用foreach循环或修改for循环,如下所示:

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