php - 如何使用 php 插入 MySQL 并回显
问题描述
我真的是 PHP 新手,需要一些帮助。
我想建立一个论坛,您可以在其中上传帖子和图片。
现在,我需要有关我的代码和 MySQL 数据库之间连接的帮助。
我将 MySQL 与下表一起使用:
主表:“帖子”
- post_data = 这是来自用户的 POST 请求。
- 用户名 = 来自另一个主表:用户
- user_id = 来自另一个主表:用户
- post_id = 自动。
我想发布从用户那里获得的数据,但我真的不知道问题出在哪里。
这是PHP代码:
<?php
session_start();
$MySQLdb = new PDO("mysql:host=127.0.0.1;dbname=forum", "root", "");
$MySQLdb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST['msg'])){
$post = $_POST['msg'];
$cursor = $MySQLdb->prepare("SELECT post_data FROM posts WHERE post=:posts_data");
$cursor->execute( array(":post_data"=>$post) );
}
$cursor = $MySQLdb->prepare("INSERT INTO posts (post) value (:post_data)");
$cursor->execute(array(":post_data"=>$post));?>
这是“msg”的 HTML 代码(帖子输入):
div class="input-group">
<input id="msg" type="text" method="POST" class="form-control" name="msg" placeholder="Write your message here...">
<span class="input-group-addon"><button id="send_post">Send</button></span>
</div>
这是我得到的错误:
注意:未定义的变量:在第 15 行的 C:\xampp\htdocs\forum\main.php 中发布
致命错误:未捕获的 PDOException:SQLSTATE [42S22]:未找到列:1054 C:\xampp\htdocs\forum\main.php:15 中的“字段列表”中的未知列“发布”:15 堆栈跟踪:#0 C:\xampp \htdocs\forum\main.php(15): PDOStatement->execute(Array) #1 {main} 在第 15 行的 C:\xampp\htdocs\forum\main.php 中抛出
非常感谢。
解决方案
你的html都是错的。
<input id="msg" type="text" method="POST" class="form-control" name="msg" placeholder="Write your message here...">
该方法是表单标签上的一个属性,而不是输入。
<form action="/youraction" method="POST" />
<input id="msg" type="text" method="POST" class="form-control" name="msg" placeholder="Write your message here...">
</form>
PHP失败,因为没有$_POST['msg']
设置
推荐阅读
- python - 为什么 tkinter 绑定事件只触发一次?
- discord.py - 如何在 discord.py 中获得命令的主要“功能”?
- javascript - 如何使用 chartjs 和 Angular 制作图表?
- csv - 如何将 Yahoo Finance 中的历史数据导入 Google 表格并使其自动更新?
- php - 如何用循环填充多维数组
- javascript - 如何在发出事件 Socket.io 后监听事件
- mysql - 如何从mysql中的group by和groupconcat其他字段中获取最大值?
- python - 数据集中的新列基于项目的最后一个值
- video-streaming - 从一个接口到另一个接口的多播路由
- gradle - 我可以获得有关 Gradle 7.0 中“隐式依赖项”的更多信息吗?