1

我正在编写一个函数来显示带有编辑和删除数据选项的表格。我需要这些表几次,所以这就是我制作函数的原因。

这是调用函数的方式:

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 个值,然后从它停止的地方继续。这怎么可能实现?

谢谢你。

4

2 回答 2

1

如果您希望主键列始终是$values数组的第一个元素,那么您可以将其称为$values[0]. 那是,

while ($table = mysql_fetch_array($result)) {
    foreach($values as $val) {
        $list .= '<td>'.$table[$val].'</td>';
    }
    $list .= '<td><a href="users.php?task=delete&user='.$table[values[0]].'">Delete</a></td></tr>';
}

我还在我认为合适的地方整理了循环。

于 2012-12-08T21:00:04.133 回答
0

您应该改用array_shift并将 $firstElement 赋值放在第一个循环中。

$firstElement = array_shift($table);

array_shift返回第一个元素而不重置数组中的索引。

于 2012-12-08T21:03:43.170 回答