【问题标题】:Inserting database array as hidden form values?将数据库数组作为隐藏的表单值插入?
【发布时间】:2017-03-11 15:25:28
【问题描述】:

我需要一些有关此代码的帮助。

在我的代码中,我有以下隐藏的表单字段作为数组:

代码:

<form action='final.php' method = 'POST'>
<input type="hidden" name="employeename" value="<?php echo $employeename; ?>">
<input type="hidden" name="ttitle" value="<?php echo $ttitle; ?>">
<input type="hidden" name="sourcename[]" value="<?php echo $_POST['sourcename' . $id]; ?>">
<input type="hidden" name="sourceaddress[]" value="<?php echo $_POST['sourceaddress' . $id]; ?>">
<input type="hidden" name="income[]" value="<?php echo $_POST['income' . $id]; ?>">
<input type="hidden" name="spousename[]" value="<?php echo $_POST['spousename' . $id]; ?>">
<input type="hidden" name="spouseAddress[]" value="<?php echo $_POST['spouseAddress' . $id]; ?>">
<input type="hidden" name="spouseIncome[]" value="<?php echo $_POST['spouseIncome' . $id]; ?>">
</form>

这些隐藏的表单字段位于名为 reviewe.php 的页面上,该页面从名为 order.php 的前一页面传递而来。

我正在尝试从名为 Finel.php 的页面插入这些表单字段的值,正如表单上的操作所指示的那样。

代码:

$sql = 'INSERT INTO `myDB`.`wp_myTable` ( `employeeID`'
     . ', `sourcename`, `sourceaddress`, `income`,`spousename`,`spouseAddress`,`spouseincome` )'
     . ' VALUES ( ? , ? , ? , ? , ? , ? , ? )';

if( $sth = mysqli_prepare($conn,$sql) ) {
   mysqli_stmt_bind_param($sth,'sssssss'
      ,$last_id
      ,$_POST["sourcename"]
      ,$_POST["sourceaddress"]
      ,$_POST["income"]
      ,$_POST["spousename"]
      ,$_POST["spouseAddress"]
      ,$_POST["spouseIncome"]
   );

执行此代码时,我收到此错误:

Notice: Array to string conversion in c:\xampp\folder\final.php

我知道这个错误意味着我有隐藏的表单字段,我试图将它们作为数组传递,但我试图将它们作为字符串插入。

但是,我不知道如何修改代码以接受变量作为数组。

有什么建议吗?谢谢。

【问题讨论】:

  • 你为什么使用数组输入名称? name="spousename[]" 看来这些都是单个值,所以为什么不简单地 name="spousename"

标签: php arrays forms


【解决方案1】:

当隐藏输入在数组中时,您可以通过简单地获取数组的第一个索引来获取它们的值。

if( $sth = mysqli_prepare($conn,$sql) ) {
     mysqli_stmt_bind_param($sth,'sssssss'
       ,$last_id
       ,$_POST["sourcename"][0]
       ,$_POST["sourceaddress"][0]
       ,$_POST["income"][0]
       ,$_POST["spousename"][0]
       ,$_POST["spouseAddress"][0]
       ,$_POST["spouseIncome"][0]
     );

【讨论】:

    【解决方案2】:

    您可以使用implode 函数通过执行以下操作将数组写入字符串:

    内爆(",", $array);

    然后使用explode 函数将其读回数组中,如下所示:

    explode(",", $array);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-07
      • 2012-11-26
      • 1970-01-01
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多