【发布时间】:2019-10-07 15:37:06
【问题描述】:
所以我有一个 CRUD 表单的代码,我可以在其中发布带有标题的主题并编辑/更新和排除,一切正常,我遇到的唯一问题是主题内容的更新,当我点击到更改已发布的主题,它只显示主题标题,但不显示内容,它仍然有效,但如果我添加另一个内容并更新,它通常会为我添加的主题更改先前发布的主题,我一直在尝试找到答案但很困难,因为我仍然只是 php 的初学者,大部分代码都是从互联网上获取的,我改变了一些东西以适应我的想法。
这是更新php代码。
<?php include('connect.php');
// get values to update
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$rec = mysqli_query($db,"SELECT * FROM news WHERE id=$id");
$record = mysqli_fetch_array($rec);
$title = $record['title'];
$content = $record['content'];
$id = $record['id'];
}
?>
html
<form method="post" action="connect.php" >
<div class="input-group">
<input type="hidden" name="id" value="<?php echo $id; ?>">
</div>
<div class="input-group">
<input type="text" name="title" placeholder="Title" value="<?php echo $title; ?>">
</div>
<div class="input-group">
<textarea name="content" placeholder="Content" value="<?php echo $content; ?>"></textarea>
</div>
<!-- form buttons -->
<div class="input-group">
<?php if ($update == true): ?>
<button class="btn" type="submit" name="update">Update</button>
<button class="btn" type="button" value="cancel" onclick="history.back();">Cancel</button>
<?php else: ?>
<button class="btn" type="submit" name="send">Send</button>
<?php endif ?>
</div>
</form>
<table>
<div class="form">
<?php while ($row = mysqli_fetch_array($results)) { ?>
<tr style="border:0;font-size:30px;";>
<td><b><?php echo $row['title']; ?></b></td>
</tr>
<tr style="border-radius: 5px;background-color: #ebebeb;">
<td><?php echo $row['content']; ?></td>
</tr>
<!-- Delete/edit buttons -->
<tr style="border:0;">
<td>
<a href="news.php?edit=<?php echo $row['id']; ?>" class="fix_btn" >Edit</a>
<a style="float:right;" href="news.php?del=<?php echo $row['id']; ?>" class="fix_btn"
onclick="return confirm('Are you sure you want to delete this topic?')">Delete</a>
</td>
</tr>
<tr style="height:60px; border:0;"><td></td></tr>
<?php } ?>
</div>
</table>
数据库连接(connect.php)
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'orbita');
// initialize variables
$title = "";
$content = "";
$id = 0;
$update = false;
if (isset($_POST['send'])) {
$title = $_POST['title'];
$contet = $_POST['content'];
mysqli_query($db, "INSERT INTO news (title, content) VALUES ('$title', '$content')");
$_SESSION['message'] = "Success!";
header('location: news.php');
}
if (isset($_POST['update'])) {
$id = $_POST['id'];
$title = $_POST['title'];
$content = $_POST['content'];
mysqli_query($db, "UPDATE news SET title ='$title', content ='$content' WHERE id=$id");
$_SESSION['message'] = "Success update!";
header('location: news.php');
}
if (isset($_GET['del'])) {
$id = $_GET['del'];
mysqli_query($db, "DELETE FROM news WHERE id=$id");
$_SESSION['message'] = "Message deleted";
header('location: news.php');
}
?>
【问题讨论】:
-
您是否在数据库中检查内容是否为空?您可以使用 phpmyadmin 轻松检查。
-
您的代码是open to SQL injection。 Use PDO and parameters。这对你来说非常紧急!
-
@Massod Aslami 是的,我已经通过表单添加了一些信息,一切正常,只是没有显示内容,这段代码只是学校的作品,所以我不太担心