以下是一个简单的新闻表单的PHP代码示例:
<!DOCTYPE html>
<html>
<head>
<title>新闻表单</title>
</head>
<body>
<h2>添加新闻</h2>
<form method="post" action="process_news.php">
<label for="title">标题:</label>
<input type="text" id="title" name="title" required><br><br>
<label for="content">内容:</label>
<textarea id="content" name="content" required></textarea><br><br>
<label for="author">作者:</label>
<input type="text" id="author" name="author" required><br><br>
<input type="submit" value="提交">
</form>
</body>
</html>
在上面的代码中,我们创建了一个简单的HTML表单来添加新闻。表单使用POST方法将数据提交到process_news.php
文件进行处理。
在process_news.php
文件中,你可以使用以下代码来处理表单数据并将其插入到数据库中:
<?php
// 连接到数据库
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接是否成功
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 获取表单数据
$title = $_POST['title'];
$content = $_POST['content'];
$author = $_POST['author'];
// 插入数据到数据库
$sql = "INSERT INTO news (title, content, author) VALUES ('$title', '$content', '$author')";
if ($conn->query($sql) === TRUE) {
echo "新闻添加成功";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// 关闭数据库连接
$conn->close();
?>
上面的代码将获取表单中的标题、内容和作者,并将它们插入到名为news
的数据库表中的对应列中。
请注意,上述代码中的数据库连接信息($servername
,$username
,$password
和$dbname
)需要根据你自己的数据库设置进行修改。
下一篇:php gd2.so
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站