将多个值发布为函数中的变量

时间:2018-09-02 12:46:56

标签: php function php-7

我试图将寄存器形式的select中的多个值发送到函数中,作为变量进行插入。我尝试使用foreach()将值作为变量发送,但仅发送最后一个值,而不发送表单中select中所有选定的值。

function addnew()
{
  $values = false;
  if (!empty($_POST['values'])) {
   $value = $_POST['values'];
   foreach($_POST['values'] as $value){
    echo "Value is:".$value."</br>";
   }
  }
}

我的代码是错误的还是通过函数发送多个值的其他方法?

编辑: 这是我完整的HTML页面(针对这种情况进行了调整)

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta http-equiv="Content-Style-Type" content="text/css">
  <title></title>
  <meta name="Generator" content="Cocoa HTML Writer">
  <meta name="CocoaVersion" content="1561.4">

</head>
<body>
<form method="post" action="submit.php?addvalue"> <!-- my action url is custom for calling function -->
<select name="values[]" multiple="multiple">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>
<input type="submit" value="Submit">
</form>

</body>
</html>

submit.php

<?php 
function addvalue()
{
    $values = false;
    if (!empty($_POST['values'])) {
        $values = $_POST['values'];
        foreach($_POST['values'] as $value){                
            echo "Value is:".$value."</br>";
           }
    }

    $data['value'] = $value;

    $model = new otherfucntion(); //class that contain other function
    $result = $model->addValue($data); //other function that do the query
    if ($result)
        {
            echo "<script>alert('".$value."</br>');</script>";//alert show value
        }
}

class otherfunction //on my case, this in otherfunction.php
{
    function conn()
    {
        //connection to db here
    }
    function addValue(($data=array()) 
    {
        extract($data);
        $sql = "INSERT INTO tablename (value) VALUES ('$value')";
            $result = mysqli_query($this->conn(), $sql);
            if (!empty($result))
            {
                return $result;
            }           
    }
}
?>

2 个答案:

答案 0 :(得分:0)

尝试使用'Robust','LAR'

,并在您的HTML中使用它:

$_POST['values[]']

答案 1 :(得分:-1)

尝试以下代码

在您的html文件中

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta http-equiv="Content-Style-Type" content="text/css">
  <title></title>
  <meta name="Generator" content="Cocoa HTML Writer">
  <meta name="CocoaVersion" content="1561.4">

</head>
<body>
<form method="post" action="submit.php">  
<select name="values[]">
  <option value="1"></option>
  <option value="1"></option>
  <option value="1"></option>
  <option value="1"></option>
</select>
<input type="submit" value="Submit">
</form>

</body>
</html>

在Submit.php文件中

<?php 
foreach($_POST['values'] as $value){
 echo "Value is:".$value."</br>";
}
?>

希望有帮助。

谢谢