我正在尝试修复一个别人编写的项目,它是一团糟!
在编辑用户配置文件页面上,他们有类似下面的东西,它将列出所有可用的选项,用户可以选择教育水平的选项,这只是1个项目,有许多类似的项目,所以根据这里的答案,我可以将它应用于此代码的许多其他功能。
他们为许多个人资料字段使用了一个数组,它将存储可能的答案,但在这种情况下,用户只能选择一个答案。所以对于教育来说,有7个可能的答案,并且数组中与它的数字相对应的数字被存储在mysql数据库中,他们将这1个数字存储为varchar 255长度,这是不好的。
我应该将它存储为一个长度为1的varchar,还是使用enum并列出7个选项,或者其他什么?
教育
<?PHP
// Array of possible education profile selections
$arr_education[1]="No Answer";
$arr_education[2]="High school";
$arr_education[3]="Some college";
$arr_education[4]="In college";
$arr_education[5]="College graduate";
$arr_education[6]="Grad / professional school";
$arr_education[7]="Post grad";
// shows the array above as checkboxes on a form
foreach($arr_education as $ind=>$val) {
echo '<input type="radio" name="education" value="' .$ind. '" ' if($education==$ind){ echo "checked";}. '>' .$val. '<br>';
}
//on a users profile page there would be something like this
$education = 7; // seven would be Post Grad from our array above
echo $arr_education[$education]
//Now here is the mysql table, they chose to use a varchar(255) which seems retarded, using the above code, the max result would be 1 charachter long
education varchar(255)
?>发布于 2009-09-04 01:45:09
如果这是一个新项目,我会推荐使用ENUM。它节省空间(它实际上存储在1个字节中),并且使用简单。但是,如果您必须支持遗留代码,那么我建议您坚持使用原始数字,并将该列更改为TINYINT。
此外,我建议将PHP源代码中的数字替换为常量,这样您就不必猜测代码是做什么的。例如:
define('EDU_NO_ANSWER', 0);
define('EDU_HIGH_SCHOOL', 1);
define('EDU_SOME_COLLEGE', 2);
// etc...
if ($education >= EDU_SOME_COLLEGE)
{
// student went to college, but you didn't need that
// comment to know that
}发布于 2009-09-03 22:19:55
为什么不使用TINY INT呢?如果答案是< 255,它更适合你的需求:)我的测试表明,它在索引和选择方面比varchrars更快。
发布于 2009-09-03 21:13:37
因此,varchar(1)将占用与varchar(255)完全相同的空间,除非枚举达到两位数,则varchar(1)将中断。最大字符数为<= 255的varchar字段存储1个字节的字符串长度,然后是字符串。因此,对于一个数字,varchar(255)需要2个字节。
然而,我不明白为什么他们没有使用其中的一个整数类。
https://stackoverflow.com/questions/1375981
复制相似问题