php - 无法正确回显数组中的数据。 PHP

标签 php mysql arrays post echo

我昨天提交了一个问题,但我认为它太长且令人困惑。今天,我缩短了所有内容并提交了我的代码示例。代码背后的想法是解析内容,将内容插入到一个表单中,该表单将在本示例中回显或插入到 mysql 数据库中。该代码运行没有错误,但仅显示单个字母和数字而不是完整单词,请参阅下面的详细信息:

  <?php
$fullstring = "Name: Steve - Age: 25, Name: Bob - Age: 30, Name: Amanda - Age: 18,"; // Content to be parsed

function get_string_between($string, $start, $end) {
    $start = preg_quote($start);
    $end = preg_quote($end);
    $pattern = "~$start\s*(.*?)$end\s*~";
    $match = preg_match_all($pattern, $string, $matches);
    if ($match) {
        return $matches[1];
    }
}

$parsed1 = get_string_between($fullstring, "Name: ", "-");
$parsed2 = get_string_between($fullstring, "Age: ", ",");


////////// The form //////////////////////

echo '<form  action="" method="POST">';
for ($i=0; $i < count($parsed1); $i++) { 
echo "Name:  <input name=\"name\" type=\"text\" value=\"". $parsed1[$i]. "\">","<br>" ;
echo "Age type:  <input name=\"age\" type=\"text\" value=\"" . strip_tags($parsed2[$i]) . "\">","<br>" ;
}

echo '<input type="submit" name="submit" value="submit">';
echo '</form>';



if (isset($_POST['submit'])) {

$i = 0;
foreach ($_POST as $value) {
    $name = $_POST['name'][$i];
    $age = $_POST['age'][$i];
echo $name.'....'.$age.'<br>';
$i++;
} 
}

//// mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
//////////////////////////////////////////////////////////////

?>

当我按下提交时,我得到了回显:

A....1
m....8
a....

Instead of of all the names in the in the form.

非常感谢大家的帮助。

最佳答案

您可以使用name[]age[]

echo '<form  action="" method="POST">';
for ($i=0; $i < count($parsed1); $i++) { 
echo "Name:  <input name=\"name[]\" type=\"text\" value=\"". $parsed1[$i]. "\">","<br>" ;
echo "Age type:  <input name=\"age[]\" type=\"text\" value=\"" . strip_tags($parsed2[$i]) . "\">","<br>" ;
}

echo '<input type="submit" name="submit" value="submit">';
echo '</form>';

if (isset($_POST['submit'])) {
  foreach($_POST['name'] as $k=>$name){       
    echo $name.'.... Age:'. $_POST['age'][$k];
  }
}

关于php - 无法正确回显数组中的数据。 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20834323/

相关文章:

c# - 执行Mysql查询时命令执行过程中遇到 fatal error

mysql - 有没有办法通过 WHERE IN 语句将嵌套子查询中的别名列名传递给 UPDATE 语句?

javascript - 向同一个对象字面量 javascript 添加不同的值

php - 在 PHP 中初始化子数组是否有必要或有用?

php - 多级 "has many"关系

php - 删除空类

php - 将 csv 文件上传到 mysql 数据库。 upload.php 文件中的错误

php - url 中的 htaccess rewriterule 2 参数

php - 选择获取每天的数据

c++ - 未分配某些元素的数组中存储了什么值?