在我的数据库 Class IV Tuition , Class VI-VIII Tuition , Engineering Subject 中存储这样的值可能是三个或五个或八个例如。我列出了三个。爆炸后$row['commonsegment']
,如何设置if
条件?
$sqledit=mysql_query("select * from tinfo where tsname='".$_SESSION['tutorname']."'");
$row=mysql_fetch_array($sqledit);
$segment = '';
$cats = explode(",", $row['commonsegment']);
foreach($cats as $cat) {
$segment .= "<category>" . $cat . "</category>\n";
}
echo $segment;
我的数据库结构:
我想这样:
<?php if($segment=='Class I-V Tuition'){echo "checked";}?>
<?php if($segment=='Class VI-VIII Tuition'){echo "checked";}?>
<?php if($segment=='Engineering Subject'){echo "checked";}?>
答案 0 :(得分:0)
您可以像其他任何地方一样制定if
条件。
$cats = explode(",", $row['commonsegment']);
foreach($cats as $cat) {
if ($cat == "Class I-V Tuition"){
// do stuff for the "Class I-V Tuition" category
} else if ($cat == "Engineering Subject"){
// do stuff for the "Engineering Subject" category
} else {
// do stuff for anything else
}
}
修改强>
好像你根本不需要foreach
循环 - 你只是在检查一个值是否在数据库结果中。
$cats = explode(",", $row['commonsegment']);
<input type="checkbox" name="segment[]" value="Class I-V Tuition" <?php if(in_array('Class I-V Tuition', $cats)) { echo "checked"; }?>> Class I-V Tuition
您可能希望在explode
上", "
,因为您的数据库似乎与逗号+空格分开,而不仅仅是逗号。