2013-03-13 53 views
3

如何在一个字段中的SQL中存储多个条目? 例如在现场手机我想让用户输入更多的手机,如私人,家庭,企业等SQL中的多个条目?

任何hellp上我如何创建trat表单和如何在sql中存储数据?

我想我可以在PHP中使用serialize()函数来存储它们,但是如何制作表单并收集该信息?

Form: 

Home Phone: 321321333 
Other: 333213213 
Add Another 

此外,我想使他们可以编辑姓名字段,所以如果用户想要把家庭电话,而不是家庭电话或传呼机,而不是其他的。

任何帮助?请?

回答

1

用户serialize()数组和对象,就像你说的。但是,对于工作添加另一个按钮,你需要JavaScript。这是一种形式:

<form action="action.php" method="post"> 
    <div id="phoneNumbers"> 
     <input type="text" value="home phone">: <input type="text" name="0-value" value="(xxx)xxx-xxxx"> 
    </div> 
    <button onclick="addAnother();">Add Another Phone Number</button> 
    <input type="submit> 
</form> 

这里是JavaScript(把你的网页的头标记):

<script type="text/javascript"> 
    var nums=0; 
    function addAnother(){ 

     document.getElementById('phoneNumbers').innerHTML+='<input type="text" name="'+++nums+'-name">: <input type="text" name="'+nums+'-value">'; 

    } 
</script> 

下面是action.php的:

<?php 
$arrayOfNums=array(); 
foreach($_POST as $curVal){ 
    array_push($arrayOfNums,$curVal); 
} 
$serializedArray=serialize($arrayOfNums); 
#now do whatever code you have to add serializedArray to your database. It is a string, so this is easy. 
?> 

现在你有一个序列化数组。只是unserialize()它,你有这样一个数组,在名称和值之间交替:'家庭电话','(324)444-4356','工作电话','(444)546-5678'等。这是未经测试的,告诉我它是否失败。

+0

任何关于如何在PHP中做到这一点的建议,如果除了手机之外,该页面上有更多的东西。那么我怎么能设置控制器上if($ this-> request->是('post')来做数组序列化只有当手机值保存? – 2013-03-13 19:03:51

3

不要在一个字段中存储多个值。你需要一个规范化的结构,这将允许多个电话号码。 1:n关系在这里是适当的。

user (userId PK) 
userPhone (userId FK, phoneType, phoneNumber (userId, phoneType PK))
+0

任何帮助,我该怎么做? – 2013-03-13 03:35:31

+1

@Miskone我会建议你阅读[这个问题](http://stackoverflow.com/questions/75105/what-datatype-should-be-used-for-storing-phone-numbers-in-sql-server-2005 )。虽然它谈到SQL Server,但它仍然适用于此。 – Kermit 2013-03-13 03:37:58

2

您可以使用json_encode()json_decode()用于保存和访问数据。

用于保存。

$phone_number = array("Home Phone" => "321321333", "Other" => "333213213"); 
$encoded = json_encode($phone_number); 

为了访问。

$result = mysqli_fetch_assoc($sql); 
$decoded = json_decode($result['phone_number_mysql_fields']); 

您可以使用PHP serialize功能存储在MySQL

+0

为什么不只是serialize()而不是json_encode?序列化是PHP原生的,json来自javascript – Markasoftware 2013-03-13 03:38:19

+0

你将如何去寻找一个电话号码? – Kermit 2013-03-13 03:39:41

+0

@Markasoftware我也编辑了答案,并提到序列化。 – 2013-03-13 03:39:45