我正在编写一个函数来显示带有编辑和删除数据选项的表格。我需要这些表几次,所以这就是我制作函数的原因。
这是调用函数的方式:
listSpecific(customer, array("CustomerID", "Forename", "Surname", "Email", "Secret Q", "Secret A", "Street", "City", "Postcode", "Type"), array("customerid", "forename", "surname", "email", "secretQ", "secretA", "address_street", "address_city", "address_postcode", "member_type"));
这是完整的功能:
function listSpecific($DBname, $titles=array(), $values=array()){
$numValues = count($values);
$i=0;
$sql = "SELECT ";
//Construct SQL Statement
foreach ($values as $val)
{
//Last Element of the array
if(++$i === $numValues){
$sql .= $val;
$sql .= " ";
}
else{
//The rest of the array elements
$sql .= $val;
$sql .= ", ";
}
}
$sql .= "FROM $DBname;";
//End of Constructing SQL Statement
// Execute Query
$result = mysql_query($sql) or die("An error has ocured: " . mysql_error() . ":" . mysql_errno());
//Construct table
$list = "<table>";
$list .= "<tr>";
//Cycle through array elements to get table headers
foreach ($titles as $title) {
$list .= "<th>$title</th>";
}
$list .= "<th>";
$list .= "Task";
$list .= "</tr><tr>";
$numValues = count($values);
$i=0;
//Construct the rest of the table [NOT WORKING]
while ($table = mysql_fetch_array($result)) {
$item = array();
foreach($values as $val){
//Last Element of the array
if(++$i === $numValues){
$list .= "<td>";
$item = $table[$val];
$list .= $item;
$list .= "</td>";
//Get the Item ID
$firstElement = reset($table);
$list .= "<td><a href=\"users.php?task=delete&user=$firstElement\">Delete</a></td></tr>";
}
else{
//The rest of the array elements
$list .= "<td>";
$item = $table[$val];
$list .= $item;
$list .= "</td>";
}
}
}
echo $list;
}
问题是创建一个删除超链接,因为我需要将传递给 URL 的用户 ID。
问题出在这一行:
//Get the Item ID
$firstElement = reset($table);
$list .= "<td><a href=\"users.php?task=delete&user=$firstElement\">Delete</a></td></tr>";
我明白为什么会出错,它会回到数组的第一项,即用户 ID。但它必须是该行唯一的。
例如,在第一行,用户 ID 是 57。但在下一行 58 上,超链接发生了变化。
一个廉价的解决方案是每次在 while 循环中返回 11 个值,然后从它停止的地方继续。这怎么可能实现?
谢谢你。