从生成的HTML表中删除行

时间:2012-06-18 17:12:12

标签: php mysql html-table

我的网站将从MySQL数据库创建一个表。我想知道他们是否可以在每行旁边有一个删除按钮,以便成员可以删除其表上的特定行。其他一切都很好。我希望用户能够从他们的表中删除他们的行。

<form action="addcel.php" method="post">
Name <input type="text" name="Name"/>
Year <input type="text" name="year"/>
<input type="submit" />

<html><head><title>MySQL Table Viewer</title></head><body>
<?php
echo "<style type = 'text/css'>

table {width:700px;border:none;text-align:center;background-color:#B0B0B0;font-family:'Arial';}

#tabledata {padding:2px;border-width:0px;}

#tableheader {border-width:0px;}

#line {border:1px solid black;padding:0px;}

</style>";
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = '';

$database = 'Name_gage';
$table = 'Name';

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 "<th id = 'tableheader'>{$field->name}</th>";
}
echo "</tr>\n";
echo "<tr><td id = 'line'></td id = 'line'><td id = 'line' ></td><td id = 'line' ></td><td id = 'line' ></td><td id = 'line' ></td></tr>";
// 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 id = 'tabledata'>$cell</td>";

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

3 个答案:

答案 0 :(得分:1)

您可以在每行中放置一个表单,以便在给定行ID的情况下调用删除脚本。

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 id = 'tabledata'>$cell</td>";
    echo "<form method='post' action='delete.php'><input type='hidden' name='id' value='$row[id]'/><input type='submit' value='Delete'/></form>";
    echo "</tr>\n";
}

答案 1 :(得分:0)

看看这个类似的stackoverflow问题:

Jquery Ajax remove rows from table and in db

上面的链接引用并解释了如何使用Ajax来实现所需的结果。

如果您愿意,您可以随时为删除行按钮创建一个onClick函数,该函数将用户链接到删除行页面,然后将用户刷新回表格页面。这就是他们在AJAX之前做到的方式,但是它是一种不那么无缝的方法。

答案 2 :(得分:0)

这需要ajax调用。当您的用户单击特定html表行的删除按钮时,您需要对服务器执行ajax调用,并在服务器端从数据库中删除该特定行。

相关问题