链接以从查询填充表单数据

时间:2014-02-21 12:45:51

标签: php mysql sql

我有一个表单,当用户从列表中选择标题时,我需要加载数据。当我保存记录时,我查询数据库并将记录的标题放在列表中,并带有编辑和删除链接。我很难在“编辑”按钮中添加“a href”,并在表单中加载记录数据。

以下是查询的代码:

<div class="content">
<ul class="nav">

<div><a href="index.html">Home</a></div>

<div class="container">
<?php
include('connect-db.php');
$result = mysql_query("SELECT * FROM 'my_table' ORDER BY id ASC");
while($row = mysql_fetch_array($result))
{
$id=$row['id'];
$title=$row['title'];
?>

<div class="show">
<Table width="300" Border="0">
<TR><TD width="260"><?php echo $title; ?></TD>

<TD width="20"><a href="#" id="<?php echo $id; ?>">EDIT</a></TD>

<TD width="20"><a href="#" id="<?php echo $id; ?>">DELETE</a>
</TD></TR>
</Table>
</div>

<?php
}
?> 
</div>

以下是表单的代码:

<form name="myForm" action="process.php" method="post">
<div>

<?php
include"connect-db.php";

$sql="SELECT * FROM my_table";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>

<input type="text" name="title" id="title" value="<? echo $rows['title']; ?>">
<textarea name="chords" id="chords" rows="1" cols="16"><? echo $rows['chords']; ?></textarea>
<textarea name="lyrics" id="lyrics" rows="4" cols="16"><? echo $rows['lyrics']; ?></textarea>

1 个答案:

答案 0 :(得分:0)

如果'process.php'应显示数据库中1条记录的结果,则需要更改链接的href并将ID作为URL中的GET参数传递给process.php。在该页面中,您需要使用该ID参数进行查询。

将链接更改为:

<a href="?action=edit&id=<?php echo $id; ?>">EDIT</a>
...
<a href="?action=delete&id=<?php echo $id; ?>">DELETE</a>

在process.php中,您需要添加一些if / else语句:

if(isset($_GET["action"]) && isset($_GET["id"]) && is_numeric($_GET["id"])) {
    include"connect-db.php";

    $sql="SELECT * FROM my_table WHERE id = " . $_GET["id"];
    $result=mysql_query($sql);
    $rows=mysql_fetch_array($result);

    if($_GET["action"] == "edit") {
        // output editing form
    }

    else if($_GET["action"] == "delete") {
        // delete
    }
}

您还可以使用不同的页面进行编辑和删除,如果这是您想要的,请相应地更改链接。在删除之前,您可能想要一个确认部分...

请注意,在URL中传递此类数据会使其非常容易受到黑客攻击。可以轻松更改ID或操作。

此外,您需要迁移代码以使用PHP的mysqli函数而不是mysql。不推荐使用mysql ...