2014-02-08 114 views
1

我想通过使用复选框在登记表单期间,通过一个条目插入一个对象数组mySQL数据库。插入复选框数组一次到MySQL查询使用PHP

此时该条目仅显示为“数组”,并且数组中没有条目。

我尝试了一个for循环,但它将整个条目插入数据库多次而不是复选框条目。

有关如何解决此问题的任何想法?

<table border="0" cellpadding="3" cellspacing="1"> 
           <tr> 
            <form id="callAjaxForm"> 
             <div data-role="fieldcontain"> 
             <td width="150">Name:</td> 
             <td width="300"><input type="text" name="inputName" value="" /> </td> 
           </tr> 
           <tr> 
            <td width="150">Username:</td> 
            <td width="300"><input type="text" name="inputUsername" value="" /></td> 
           </tr> 
           <tr> 
            <td width="150">Password:</td> 
            <td width="300"><input type="password" name="inputPassword" value="" /></td> 
           </tr> 
           <tr> 
            <td width="150">Date of Birth:</td> 
            <td width="300"><input type="date" name="inputDOB" value="" /></td> 
           </tr> 
           <tr> 
            <td width="150">Core Competencies:</td> 
            <td width="300"> 
             <input type="checkbox" name="coreComp[]" value="1" />Honesty<br /> 
             <input type="checkbox" name="coreComp[]" value="2" />Loyalty<br /> 
             <input type="checkbox" name="coreComp[]" value="3" />Trust<br /> 
             <input type="checkbox" name="coreComp[]" value="4" />Empathy<br /> 
             <input type="checkbox" name="coreComp[]" value="5" />Respect</td> 
           </tr> 
           <tr> 
            <td colspan="2"> 
             <button data-theme="b" id="submit" type="submit">Submit</button> 
            </td> 
            </tr> 
           <tr> 
            <td colspan="2"> 
             <h3 id="notification"></h3> 
             </td> 
           </tr> 
           </div> 
           </form> 
          </table> 

PHP代码

<?php 
include 'includes/Connect.php'; 

$name = $_POST['inputName']; 
$username = $_POST['inputUsername']; 
$password = $_POST['inputPassword']; 
$dob = $_POST['inputDOB']; 
$aCC = $_POST['coreComp']; 

$encrypt_password=md5($password); 

if(empty($aCC)) 
{ 
    echo("Please pick at least one"); 
} 
else 
{ 
    mysql_query("INSERT INTO Profile (`Name`,`Username`,`Password`,`D.O.B`,`CC`) VALUES('$name','$username','$encrypt_password','$dob','$aCC')") or die(mysql_error()); 
    mysql_close(); 

    echo("You have successfully registered!"); 
} 
?> 
+0

你的复选框coreComp是一个数组,所以是的,如果你尝试直接插入,这是行不通的。你想如何为每个选定的项目或全部插入一行? –

+0

这是一个数组(至少当他们中的至少一个被选中时...)。你想如何存储它,都在同一列?如果是这样,你需要序列化数组或类似的,但这使得搜索痛苦。 – jeroen

回答

0

使用内爆并爆炸。

$aCC = implode(';' , $_POST['coreComp']); 
$aCC will contain all values glued together with a ';' in between them. 

有了这个,你可以将它存储在数据库中。当您从数据库检索数据时,请确保使用爆炸。

http://nl1.php.net/manual/en/function.explode.php

+0

非常感谢。工作过一种享受。 – Phughes

+0

如果你不介意,你能设置这个答案,如果这对你有帮助吗? – Rimble

0

无法存储阵列,您可以用逗号Concat的和在PHP中使用破灭()函数将其插入到该领域。 Check here

另一种方法是将核心竞争力与值保持在单独的表格中,并使用复选框中的唯一ID填充相同的复选框,这样您就可以将字段中的ID存储为以逗号分隔的字段。

希望这会有所帮助。