对于radio或着checkbox等form表单元素,有的时候,我们不仅希望存贮他们的值,有的时候,希望也存贮他们的label。举个例子男:
女:
我们希望不但可以存贮他们的选中的值,未选中的值也需要存贮进去。比如,上面例子中,我们不但要存入m这个选中的值,还要把f这个未选中的值存起来,同时也希望把男和女这两个label存起来。那么我们可以这样设计数据库。create table html_tag(
id int(4) not null primary key auto_increment,
html_tags char(100) not null,
value int(4) not null default '0');
insert into html_tag(1,'{"男":m,"女":f}',m);
上面我们就把所有radio存到数据库中了,并且存入了默认值m.下面给出如何调用它,在前台,这里使用php的语法来实现。<?php
$con = mysql_connect("localhost","root","root");
if(!$con){
die("不能连接数据库".mysql_error());
}
mysql_select_db("temp");
$res = mysql_query('select * from html_tag where id=1');
while($result = mysql_fetch_array($res)){
$tag = $result['html_tags'];
$tag_json = json_decode($tag);
foreach($tag_json as $key=>$val){
$html = $key.':
if($val==$tag['value']){
echo $html. "checked='checked'/>";
}
}
}
通过上面的例子,我们就把html的结构存入数据库了,设计的时候我们还可以把name,和type也存入到数据库,到时候更具type的类型,来在前段通过switch进行html的重绘,这样通过一张表的一条记录就把多个radio或着checkbox存入起来了。
这里实现的核心就是将html结构通过json存贮,这样可以用php等语言方便数据格式的转换了。