MySQLi实现新闻的基本操作

1 开发思路

创建表单:编写添加新闻页面。
查询作者:将数据表author中的信息读取出来。
显示作者:在添加新闻表单中添加下拉列表框,显示作者信息。
保存新闻:当用户在添加新闻页面提交表单后,向news表插入数据。

2 编写添加新闻页面

<div class="add-news col-md-8 col-md-offset-2">
<h1>添加新闻</h1>
<form action="insert.php" method="post">
<div class="form-group">
<label for="news_title">新闻标题</label>
<input type="text" class="form-control" id="news_title" name="title">
</div>
<!-- 作者列表 -->
<div class="form-group">
<label for="news_content">新闻内容</label>
<textarea class="form-control" rows="12" name="content"></textarea>
</div><button class="btn btn-primary btn-block">添加</button>
</form>
</div>

3 将数据表author中的信息读取出来

$link = mysqli_connect('localhost', 'root', '123456', 'news', '3306');
if (!$link) {
exit(mysqli_connect_error());
}
if (!mysqli_set_charset($link, 'utf8')) {
exit(mysqli_error($link));
}
// 获取作者信息
$result = mysqli_query($link, 'SELECT `id`,`name` FROM `author`');
if (!$result) {
exit(mysqli_error($link));
}
$authors = [];
while ($row = mysqli_fetch_assoc($result)) {
$authors[] = $row;
}

4 在添加新闻表单中添加下拉列表框,显示作者信息

<div class="form-group">
<label for="news_author">作者</label>
<select name="author">
<?php foreach($authors as $author):?>
<option value="<?php echo $author['id'];?>">
<?php echo $author['name'];?>
</option>
<?php endforeach;?>
</select>
</div>

5 接收用户提交表单的表单数据

<?php
$title = $_POST['title'] ?? '';
$content = $_POST['content'] ?? '';
$a_id = $_POST['author'] ?? 0;
// 判断标题和内容是否为空
if (empty($title) || empty($content)) {
header('refresh:3;url=add.php');
echo '新闻标题和内容都不能为空!';
exit;
}

6 向news表插入数据

// 省略连接数据库和设置字符集步骤
$sql = 'INSERT INTO `news` VALUES(NULL, \'' . $title . '\', \'' .
$content . '\', ' . $a_id . ',' . time() . ')';
$res = mysqli_query($link, $sql);
if ($res) {
header('refresh:2;url=index.php');
echo '新闻:' . $title . ' 新增成功!';
} else {
header('refresh:3;url=add.php');
echo '新闻:' . $title . '新增失败!';
}


相关推荐

  • 生成图片

    from PIL import Image, ImageColor, ImageDraw, ImageFont, ImageFilterdef create_image_with_text(size, color, text, font_path, font_size, text_color, shadow_color, output_path): """ Create a new image of specified size and color with centered text that has a border and shadow. :param size: A tuple con

  • 获取指定目录下的所有图片信息

    1 获取指定目录下的所有图片信息// 获取指定目录下的所有图片信息 public function getImagesInfo($directory) { $images = []; // 创建递归目录迭代器 $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($directory, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY ); // 遍历目录中的每个文件 foreach (

  • Thinkphp各版本的PHP要求

    ThinkPHP 8.0:运行环境要求PHP8.0+,兼容PHP8.3ThinkPHP 6.1:运行环境要求PHP7.2+,兼容PHP8.1ThinkPHP 6.0:运行环境要求PHP7.2+,兼容PHP8.1ThinkPHP 5.1:运行环境要求PHP5.6+,兼容PHP8.0ThinkPHP 5.0:运行环境要求PHP5.4+,兼容PHP7.3