I'm writing a function to display tables with the option of editing and deleting the data. I need these tables a few times so this is why I made a function.
This is how the function is called:
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"));
This is the function in its entirety:
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;
}
The issue is creating a delete hyperlink as I need the user ID which will be passed to the URL.
The issue is on this line:
//Get the Item ID
$firstElement = reset($table);
$list .= "<td><a href=\"users.php?task=delete&user=$firstElement\">Delete</a></td></tr>";
I understand why it's going wrong, it will go back to the very first item of the array, which is the User ID. But it needs to be unique to the row.
For example, on the first row the user ID is 57. But on the next row 58 and have the hyperlink change.
A cheap solution to this would be to go back 11 values every time in the while loop and then continuing from where it left off. How could this be achieved?
Thank you.