使用PHP将表单数组添加到MySQL

时间:2015-07-14 13:17:01

标签: php mysql

我无法以'arrayitem1,arrayitem2等'格式将数组放入MySQL数据库......

以下是我的表格:

<form action="http://www.nccskills.co.uk/bookings/process.php" method="post" name="bookingForm">
  <div id="row12">
    <div class="col1">
      <input type="checkbox" name="vocCheck[]" value="HASA">
      &nbsp;&nbsp;HEALTH AND SAFETY AWARENESS
    </div>
    <div class="col2">
      <input type="checkbox" name="vocCheck[]" value="EAD">
      &nbsp;&nbsp;EQUALITY AND DIVERSITY
    </div>
  </div>
  <div id="row13">
    <div class="col1">
      <input type="checkbox" name="vocCheck[]" value="ECC">
      &nbsp;&nbsp;EFFECTIVE CUSTOMER CARE
    </div>
    <div class="col2">
      <input type="checkbox" name="vocCheck[]" value="CC">
      &nbsp;&nbsp;CARE CERTIFICATE</div>
    </div>

我会用什么PHP来实现这个目标?

提前致谢。

1 个答案:

答案 0 :(得分:1)

process.php文件中,您希望代码看起来像这样:

//Create a connection using MySQLi
$conn = new mysqli($servername, $username, $password, $dbname);

//Prepare a statement.
$conn->prepare('INSERT INTO tablename(fieldname) VALUES(?)');

//Put all the checkboxes together, if anything is selected.
$checked = '';
if(is_array($_POST['vocCheck'])) {
    $checked = implode(',', $_POST['vocCheck']);
}

//Bind the value.
$conn->bind_param('s', $checked);

//Execute the question.
$conn->execute();

不是100%确定你确实需要检查$_POST['vocCheck']是否是一个阵列而且我现在无法尝试,所以我把它包括在内是为了安全起见。如果连接不起作用,您可能需要将一些错误处理抛入其中。等一些有用的链接: