Louis_Jay 2021-12-24 17:35 采纳率: 100%
浏览 30
已结题

为什么表单提交之后没有录入SQL库里,而且提示失败

问题遇到的现象和发生背景

为什么表单提交之后没有录入SQL库里,而且提示失败

问题相关代码,请勿粘贴截图

add.php

<?php
require './config.php';
require './check_from.lib.php';
require './denglucheck.php';
//有表单数据提交
if(!empty($_POST)){
    $title = trim($_POST['title']);
    $con = $_POST['contents'];
  $sql = "INSERT INTO `wenzhang`( `title`, `contents`) VALUES ('$title','$con')";
    $res = mysqli_query($link, $sql); //返回布尔值
     if($res){
     // echo "插入成功";
     header('Location:./index.php');
  }else{
      echo "插入失败";
  }
}

xinjian_html.php


<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
    .box{width: 800px; height: 800px;}
</style>
</head>
<body>
    <form method="post" action="add.php" enctype="multipart/form-data" name="from1">
    <div class="box">
            标题:<br>
            <input type="text" name="title"><br><br>
            内容:<br>
            <textarea rows="10" cols="100" name="contents"></textarea><br><br>    
            <input type="submit" value="发表" id="btn" class="btn">        
    </div>
    </form>
</body>
</html>

运行结果及报错内容

插入失败

我想要达到的结果

可以加载主页并且能插入成功

  • 写回答

1条回答 默认 最新

  • 明日晴空 2021-12-25 02:37
    关注

    插入失败原因:
    1、数据库连接失败
    2、sql语句错误
    查看原因:
    使用mysqli_error()方法查看具体错误原因;

    【你的原因】
    1、没有看到你$link连接数据库的代码,给你改造了下

    <?php
    require './config.php';
    require './check_from.lib.php';
    require './denglucheck.php';
    //有表单数据提交
    if(!empty($_POST)){
      // 参数对应:数据库地址、用户名、密码、数据库名(以下改成自己的)
      $link = mysqli_connect("localhost","root","passwrod","dbname"); 
      $title = trim($_POST['title']);
      $con = $_POST['contents'];
      $sql = "INSERT INTO `wenzhang`(`title`, `contents`) VALUES ('$title','$con')";
      $res = mysqli_query($link, $sql); //返回布尔值
      if($res){
         // echo "插入成功";
         header('Location:./index.php');
      }else{
          echo "插入失败:" . mysqli_error($link);
      }
    }
    
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 1月2日
  • 已采纳回答 12月25日
  • 创建了问题 12月24日