我正在編寫一個函數來顯示帶有編輯和刪除數據選項的表。我需要這些表幾次,所以這就是爲什麼我做了一個功能。嘗試將數組重置爲行的第一個值
這是該函數的調用:
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;
}
的問題是創建一個刪除超級鏈接,因爲我需要的用戶ID將被傳遞給URL。
的問題是在這條線:
//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個值,然後從中斷處繼續。這怎麼可能實現?
謝謝。
在我看來'$ values'是一個表列名稱的數組,所以肯定它會是'$ table [$ values [0]]'? – Crisp
謝謝,它工作完美,比我原來的代碼更清潔! (我不能投票,我沒有足夠的代表對不起) –