【问题标题】:How to save multiple data from dynamically added text-boxes (JavaScript) into MySQL database?如何将动态添加的文本框(JavaScript)中的多个数据保存到 MySQL 数据库中?
【发布时间】:2012-05-01 10:24:20
【问题描述】:

我一直在尝试,但没有成功。我正在使用 PHP、HTML、JavaScript 和 MySQL。这是我的 HTML 代码:

<div id="Author">
    <LI>Author</LI> 
    <input type = "text" name="Author[]" value = "1. "/>
    <input type="button" value="+" id="Authorbutton" onclick="addAuthor()" />
</div>

如果单击添加按钮,将出现另一个文本框,用户并输入另一个名称。这是我的 JavaScript:

var counter3 = 0;
function addAuthor() {
    // Get the main Div in which all the other divs will be added
    var mainContainer = document.getElementById('Author');

    // Create a new div for holding text and button input elements
    var newDiv = document.createElement('div');

    // Create a new text input
    var newText = document.createElement('input');
    newText.type = "text";
    //var i = 1;
    newText.name = "Author[]";
    newText.value = counter3 + 2 + ". ";

    //Counter starts from 2 since we already have one item
    //newText.class = "input.text";
    // Create a new button input
    var newDelButton = document.createElement('input');
    newDelButton.type = "button";
    newDelButton.value = "-";

    // Append new text input to the newDiv
    newDiv.appendChild(newText);
    // Append new button input to the newDiv
    newDiv.appendChild(newDelButton);
    // Append newDiv input to the mainContainer div
    mainContainer.appendChild(newDiv);
    counter3++;
    //i++;

    // Add a handler to button for deleting the newDiv from the mainContainer
    newDelButton.onclick = function() {
        mainContainer.removeChild(newDiv);
        counter3--;
    }
}

这是我的 PHP 代码:

if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db($database, $con);



$sql="INSERT INTO savetest (type, number)
VALUES
('$_POST[type]','$_POST[Author]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

mysql_close($con);
echo "Thank you for submitting your details!";

我听说很多人可以通过使用数组来实现这一点,但我存储在数据库中的数据是Array。我创建了多少个文本框并不重要,只需Array

我是否使用了正确的方法?我应该将这组数据保存在一个数据库字段中吗?

【问题讨论】:

  • GeorgioCZY,我已经阅读了三遍以上,但我仍然无法弄清楚您在问什么。您希望出现另一个文本字段吗?不是出现了吗?此外,您的代码有几个格式问题。请修改,它会更容易提供帮助。
  • 如果要将所有数据保存到一个字段,则需要 implode data implode(',', $_POST[Author])。
  • @BrendonCheves 我的 javascript 添加文本框已经工作,我只想将所有输入保存到 Mysql 中。现在,它只保存第一个输入。如果我使用数组,则只会保存文本“数组”。我的问题是如何将所有这些数据保存到 mysql 中。我不确定是否应该将所有这些文本框数据保存到一个字段中。

标签: php javascript mysql html


【解决方案1】:
if (!$con){
   die('Could not connect: ' . mysql_error());
}

mysql_select_db($database, $con);

$authors = $_POST['Author'];
foreach($authors as $author) :
    $sql="INSERT INTO savetest (type, number) VALUES ('{$_POST['type']}','{$author}')";

    if (!mysql_query($sql,$con)){
       die('Error: ' . mysql_error());
    }
endforeach;

【讨论】:

猜你喜欢
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多