简体   繁体   中英

Adding delete button to php code displaying mysql table contents

I have searched for an answer that relates to my code but I'm new to php and html so I would appreciate the help.

So I've created code that uses loops to display a html table with the contents of the specified table from a mysql database. I would like to give the user an option to delete a row when the results are displayed.

This is my code so far to display the results of my database table:

<html><head><title>MySQL Table Viewer</title></head><body>
<?php
$db_host = 'localhost';
$db_user = 'username'; 
$db_pwd = 'password';

$database = 'dvdproject'; 
$table = 'Employee';
$con= mysql_connect($db_host,$db_user,$db_pwd,$database);
if(!$con){
die("Can not connect" . mysql_error()); 
}
mysql_select_db($database,$con);


// sending query
$result = mysql_query("SELECT * FROM {$table}");

$fields_num = mysql_num_fields($result);

echo "<h1>Table: {$table}</h1>";
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";


foreach($row as $cell)
echo "<td>$cell</td>";
echo '<form method="POST" name="deleterequest" action =
"deleterequest.php">';
        echo "<input name='record_id' type='hidden' value='".$row['id']."'
 >";
        echo "<input name='delete'type='submit' value='Delete' >";
        echo "</form>";

echo "</tr>\n";

}
echo "</table>";
mysql_close($con);
?>

No matter where I place my form to delete button, 6 delete buttons take up an entire row followed by the actual rows. I would like the delete button to be after each row but I just cant get my head around it!

Apologies if I am overlooking something here, but have you tried wrapping your delete button with <td> tags?

foreach($row as $cell)
    echo "<td>$cell</td>";
    echo "<td>"; 
    echo '<form method="POST" name="deleterequest" action="deleterequest.php">';
    echo "<input name='record_id' type='hidden' value='".$row['id']."'>";
    echo "<input name='delete'type='submit' value='Delete' >";
    echo "</form>";
    echo "</td>";
    echo "</tr>\n";
}

I stripped everything bar HTML away from this and found a <td> tag around the form worked a treat.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM