PHP回显MySQL数据库字段和复选框

时间:2012-06-14 13:43:41

标签: php mysql foreach while-loop echo

我已经将此代码设计为回显特定位置的人员列表。然后,您可以通过选中其名称旁边的复选框来分组所有这些人,并提交将使用新组更新数据库的表单。听起来很简单。但不幸的是,数据库是使用许多彼此关联的表来设置的。所以它有点复杂。这是我到目前为止所做的:

<?php

//Query the database for the Location ID of the currently logged in user

$query1 = mysql_query("SELECT * FROM `Location` WHERE Name = '".$_SESSION['Location']."'");
$array1 = mysql_fetch_array($query1);

//Query the database for the all the participants in this location, make an array of the results and then implode the array

$query2 = mysql_query("SELECT idParticipant FROM `Participant/Location` WHERE idLocation = ".$array1['idLocation'].";");
$column1 = array();
while($row = mysql_fetch_array($query2)){
$column1[] = $row['idParticipant'];
}
$values = implode(' OR ', $column1);

//Query database for all first names where the particpant ID's equal those of the above $values

$query3 = mysql_query("SELECT firstName FROM `Participant` WHERE idParticipant = $values;");
$columnFirstName = array();
while($row = mysql_fetch_array($query3)){

$columnFirstName[] = $row['firstName'];

}

foreach($columnFirstName as $value){

echo "<input type='checkbox' name='check[]' id='' value='' />";
echo $value."<br><br>";

}


?>
<input type="submit" name="submit" value="Save New Group"> 

</form>

因此,上面的代码回显了该位置的所有名字,并在其旁边添加了一个复选框。问题是我需要第二个名字出现在名字旁边。我需要获取每个人的ID以输入复选框的值。

我不知道我怎么能这样做...我想我需要对第二个名字进行第二次查询然后调整我的foreach循环......我可能需要一个全新的foreach循环我不会吗?

1 个答案:

答案 0 :(得分:0)

这就是我需要做的事情:

$query3 = mysql_query("SELECT * FROM `Participant` WHERE idParticipant = $values;");
$columnFirstName = array();
$columnSecondName = array();
$columnID = array();
while($row = mysql_fetch_array($query3)){

$columnFirstName[] = $row['firstName'];
$columnSecondName[] = $row['secondName'];
$columnID[] = $row['idParticipant'];

}

for($i=0;$i<count($columnFirstName);$i++) {

 $firstName  = $columnFirstName[$i];
 $secondName = $columnSecondName[$i];
 $id = $columnID[$i];

 echo "<input type='checkbox' name='check[]' id='$id' value='$id' />";
 echo $firstName." ";
 echo $secondName."<br><br>";

}

?>

<input type="submit" name="submit" value="Save New Group"> 

</form>