【问题标题】:MySQL database is not receiving any data in PHPMySQL 数据库未在 PHP 中接收任何数据
【发布时间】:2021-08-19 03:20:44
【问题描述】:

我创建了两个类:一个名为 index.php 的类,供用户输入数据,例如:姓名、电子邮件、电话号码和地址。 另一个名为 model.php 的类必须将用户键入的信息发送到 MySQL 数据库中。 但是,当用户在图形界面中输入信息,然后单击提交按钮时,本地 MySQL 数据库没有接收到数据。 数据库的名字叫“crud”,crud里面的数据库表的名字叫:“gravacoes”。

请问,谁能帮帮我?

index.php 代码:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
    <title>Hello, world!</title>
  </head>
  <body>
  <div class = "container">
    <div class = "row">
      <div class = "col-md-12 mt-5">
        <h1 class = "text-center">PHP OOP CRUD TUTORIAL</h1>
        <hr style = "height: 1px; color: black; background-color:black;">
      </div>
    </div>
    <div class = "row">
      <div class = "col-md-5 mx-auto">
        <?php
        include 'model.php';
        $model = new Model();
        $insert = $model->insert();
        ?>
        <form action = "" method = "post">
          <div class = "form-group">
            <label for = "">Name</label>
            <input type = "text" name = "name" class = "form-control">
        </div>

          <div class = "form-group">
            <label for = "">Email</label>
            <input type = "email" name = "email" class = "form-control">
          </div>

          <div class = "form-group">
            <label for = "">Mobile No.</label>
            <input type = "text" name = "mobile" class = "form-control">
          </div>

          <div class = "form-group">
            <label for = "">Address</label>
            <textarea name ="address" id = "" cols = "" rows = "3" class = "form-control"></textarea>
            <br />
          </div>

          <div class = "form-group">
            <button type = "submit" name = "submit" class = "btn btn-primary">Submit</button>
          </div>
        </form>
      </div>
    </div>
  </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
  </body>
</html> 

model.php的代码:

<?php
class Model {
    private $server = "localhost";
    private $username ="root";
    private $password;
    private $db = "crud";
    private $conn;

    public function __construct(){
        try {
            $this->conn = new mysqli($this->server, $this->username, $this->password, $this->db);
        } catch (Exception $e){
            echo "Connection failed". $e->getMessage();
        }
    }

    public function insert() {
        if(isset($_POST['submit'])) {
            if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['mobile']) && isset($_POST['address'])) {
                if(!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['mobile']) && !empty($_POST['address'])) {

                    $name =  $_POST['name'];
                    $mobile = $_POST['mobile'];
                    $email = $_POST['email'];
                    $address= $_POST['address'];    

                    $query = "INSERT INTO gravacoes (name, email, mobile, address) VALUES ('$name', '$email', '$mobile', '$address')";

                    if ($sql = $this->conn->query($query)) {
                        echo "<script>alert('Success');</script>";
                        echo "<script>window, location.href = 'index.php';</script>";
                    } else {
                        echo "<script>alert('Failed');</script>";
                        echo "<script>window.location.href='index.php';</script>";
                    }
                    
                } else {
                    echo "<script>alert('Empty');</script>";
                    echo "<script>window.location.href = 'index.php';</script>";
                }

            }
        }
    }
}
?>

【问题讨论】:

  • 我在index.php 中没有看到课程。
  • 您在index.php 中没有在提交表单时调用Model 类的代码。
  • 您的代码对 SQL 注入开放。您应该使用带参数的预处理语句,而不是直接将变量替换到 SQL 字符串中。
  • Barmar,请检查 index.php 中的第 19-23 行: insert(); ?>
  • 谢谢,我错过了。将代码混合到 HTML 的中间是令人困惑的。

标签: php html mysql database forms


【解决方案1】:

你做的几乎所有事情都是对的,有一点不对是你试图从数据库连接中捕获异常,而 mysqli 对象默认不会抛出任何异常,所以首先尝试启用错误报告:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$this->conn = new mysqli($this->server, $this->username, $this->password, $this->db);

SQL 注入警告:

您应该使用准备好的语句将数据插入数据库以防止 SQL 注入,例如:

$query = "INSERT INTO gravacoes (name, email, mobile, address) VALUES (?, ?, ?, ?)";

$st = $this->conn->prepare($query);

$st->bind_param("ssss", $name, $email, $mobile, $address);

$st->execute();

这就够了,但我更喜欢使用 PDO 来处理这种逻辑,而且你可以将验证与模型分开,所以我为你做了另一个实现,不是最好的,只是为了让你上路:

首先是你的模型:它是相同的,但如果你将数据库连接与你的模型分开会更好:

model.php

class Model
{
    private $server = "localhost";

    private $username = "root";

    private $password = '';

    private $db = "crudd";

    private $conn;

    public function __construct()
    {
        try {
            $this->conn = new PDO("mysql:host=$this->server;dbname=$this->db", $this->username, $this->password);
        } catch (PDOException $e) {
            die('DATABASE CONNECTION ERROR: ' . $e->getMessage());
            //or you can throw your own exception to catch later
        }
    }

    public function insert($data)
    {
        $query = "INSERT INTO gravacoes (name, email, mobile, address) VALUES (:name, :email, :mobile, :address)";

        $res = $this->conn->prepare($query);

        $res->execute($data);

        return $res->rowCount(); // return number of affected rows, in this case return 1
    }
}

然后我添加了一个处理表单逻辑的文件

functions.php

function handle_form()
{
    if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['mobile']) || empty($_POST['address'])) {
        throw new Exception("All fields must be filled");
    }

    // all filed are filled we can now include the model:

    $data = []; //empty array will populate with data

    $data['name'] = $_POST['name'];

    $data['email'] = $_POST['email'];

    $data['mobile'] = $_POST['mobile'];

    $data['address'] = $_POST['address'];

    require_once 'model.php';

    $model = new Model();

    $model->insert($data);
}

然后在你的 HTML 中

index.php

....
<div class="container">
    <div class="row">
        <div class="col-md-12 mt-5">
            <h1 class="text-center">PHP OOP CRUD TUTORIAL</h1>
            <hr style="height: 1px; color: black; background-color:black;">
        </div>
    </div>
    <div class="row">
        <div class="col-md-5 mx-auto">
            <?php
            include 'functions.php';
            if (isset($_POST['submit'])) {
                try {
                    handle_form();
                } catch (Exception $e) {
                    echo "<script>alert('" . $e->getMessage() . "');</script>";
                    echo "<script>window.location.href='index.php';</script>";
                    return;
                }

                echo "<script>alert('Success');</script>";
                echo "<script>window, location.href = 'index.php';</script>";
            }

            ?>
            <form action="" method="post">
                <div class="form-group">
                    <label for="">Name</label>
                    <input type="text" name="name" class="form-control">
                </div>
          ....

【讨论】:

  • mysqli 确实会抛出异常。这是推荐的模式。请不要手动检查错误。阅读stackoverflow.com/questions/14578243/…
  • 仅供参考,如果您不打算从错误中恢复,捕获异常通常不是一个好主意。我删除了它们。我离开了你真正从中恢复的那个,但这是一种糟糕的做法,因为你基本上会丢失信息。你永远不应该捕获这样的异常
  • 那么如果执行失败呢?
  • 如果执行失败,那么 PHP 会抛出一个错误。用户不需要知道什么是语法错误。他们只需要知道错误已记录在服务器上,管理员将查看它
  • 确保用户不需要知道 PDO 正在抛出的异常,并且在您编辑的答案中您没有捕获它,因此它将被抛出并且没有什么可以捕获它,所以如果我们使用您在生产中的代码我们将遇到安全问题(未捕获的异常 PDO...)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-25
  • 1970-01-01
  • 2018-11-04
  • 2011-09-05
  • 2016-06-17
相关资源
最近更新 更多