【问题标题】:Array value cannot insert more than one data数组值不能插入多个数据
【发布时间】:2017-04-11 08:21:27
【问题描述】:

我使用此代码插入数组值。但是,它只插入一行而不是 2 或 3 行。我的编码有什么问题吗?

<input type="text" size="45" name="description[]" id="description" placeholder="description">

if(isset($_POST['submit']))
{
    $description = array();

    if(is_array($description))
    {
        foreach($_POST['description'] as $key1=>$value1)
        {   
            $description[]=$value1;
        }
    }

    for($loop = 0; $loop < count($description); $loop++)
    {
        if($description[$loop]=="" || $description[$loop]==null)
            $error=1;
    }

    if(isset($error))
    $error=1;
    else
    $error=0;

    if($error==0)
    {   
        for ($i = 0; $i < count($description); $i++)
        {

            $sqlfam = "INSERT INTO productorder (description)
            VALUES ('". $description[$i] ."')";
            mysql_query($sqlfam) or die ("Error: " . mysql_error());
        }
    }
}

请帮忙,谢谢。

【问题讨论】:

  • 你能显示 $description 的价值吗?
  • 真的确定$_POST['description']实际上是一个数组吗?从技术角度来看,这是可能的,但不太可能。请在问题中添加$_POST 超全局变量的转储。
  • mysql_* 函数自 PHP 7 起已被删除,不应再使用。而是使用mysqliPDO
  • 当您刚刚在语句上方设置$description - array() 时,您的is_array($description) 条件有什么意义? if 语句是多余的,因为它总是正确的。也许你的意思是测试is_array($_POST['description'])
  • amln_ndh 如果某个答案解决了您的问题,请考虑接受该答案。以下是meta.stackexchange.com/questions/5234... 的方法,然后返回此处,对勾号/复选标记执行相同操作,直到它变为绿色。这通知社区,找到了解决方案。否则,其他人可能会认为问题仍然悬而未决,可能想要发布(更多)答案。您将获得积分,并鼓励其他人帮助您。谢谢!

标签: php mysql arrays sql-insert


【解决方案1】:

我自己假设描述值。

if(isset($_POST['submit']))
{
    $description = array();

    if(is_array($description))
    {
        foreach($_POST['description'] as $key1=>$value1)
        {   
            $description[]=$value1;
        }
    }
    $error = 0 ;

    for($loop = 0; $loop < count($description); $loop++)
    {
        if($description[$loop]=="" || $description[$loop]==null){
          continue;
        }
        else{
          $sqlfam = "INSERT INTO productorder (description)
            VALUES ('". $description[$i] ."')";
            mysql_query($sqlfam) or die ("Error: " . mysql_error());
        }

    }

}

【讨论】:

  • 应该continue;实际上是来自循环的break;吗?
  • 我使用 continue 因为如果 value 为空或 null 它继续循环意味着。如果在第一次迭代中发现 null 或空白,我将使用 break,它将退出循环。
  • 我认为我们在同一页上,只是一个小错字。因为你知道它会永远按照你的逻辑继续下去。如果它没有进入 if 语句,它仍然会继续,而且我认为你的意思是为你的 if 条件添加 not null
猜你喜欢
  • 2013-04-13
  • 1970-01-01
  • 1970-01-01
  • 2014-12-02
  • 2021-07-25
  • 1970-01-01
  • 2021-04-12
  • 1970-01-01
相关资源
最近更新 更多