简体   繁体   中英

MYsql in a HTML table. Delete row

I'm using PHP to display what is in my MYsql database in a table. I would like to add a delete button buy I don't know how. I would like the delete button right after the last column. Here is my code.

<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = '';

$database = 'coins_gage';
$table = 'coins';

if (!mysql_connect($db_host, $db_user, $db_pwd))
    die("Can't connect to database");

if (!mysql_select_db($database))
    die("Can't select database");

// sending query
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
    die("Query to show fields from table failed");
}

$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>";

    // $row is array... foreach( .. ) puts every element
    // of $row to $cell variable
    foreach($row as $cell)
        echo "<td>$cell</td>";

    echo "</tr>\n";
}
mysql_free_result($result);
?>

You have to do several things here to make the interface user friendly and perform your task. If I summarize the steps you have to do is like this.

1) Make sure you keep your table inside a form with POST method. And add following kind of hidden elements just before close the FORM tag.

<input type="hidden" name="hidDelete" id="hidDelete" value="" />

2) Add a column header to the table by modifying this section.

// printing table headers  
for($i=0; $i<$fields_num; $i++)  
{  
    $field = mysql_fetch_field($result);  
    echo "<td>{$field->name}</td>";  
}  
echo "<td>Delete</td>";  
echo "</tr>\n";   

3) Add the delete button to all the rows.

foreach($row as $cell)  
    echo "<td>$cell</td>";  
echo "<td><input type=\"button\" value=\"Delete\" onclick=\"deleteThis({$field->id})\" /></td>"  
echo "</tr>\n";  

4) The create a javascript function to make the delete request. Before you post data you have to set a hidden value. If you use javascript library like jquery this will be much easier. Since I don't know which library you are using I will explain in pure javascript.

<script type="text/javascript">  
function deleteThis(id)  
{  
    document.getElementById("hidDelete").value = id;  
    document.yourFormName.submit();  
}  
</script>  

5) Once you get the post request to your page, Make the deletion before you do select queries.

if(isset($_POST["hidDelete"]) $_POST["hidDelete"] != "")  
{  
    $rowID = $_POST["hidDelete"];  
    // Write your delete queries  
}  

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