首页 > 解决方案 > 如何使用 php 插入 MySQL 并回显

问题描述

我真的是 PHP 新手,需要一些帮助。

我想建立一个论坛,您可以在其中上传帖子和图片。

现在,我需要有关我的代码和 MySQL 数据库之间连接的帮助。

我将 MySQL 与下表一起使用:

主表:“帖子”

  1. post_data = 这是来自用户的 POST 请求。
  2. 用户名 = 来自另一个主表:用户
  3. user_id = 来自另一个主表:用户
  4. 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 中抛出

非常感谢。

标签: phpmysqlsql

解决方案


你的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']设置


推荐阅读