Skip to content
Advertisement

MySQL database is not receiving any data in PHP

I created two classes: a class called index.php for a user to input data such as: name, email, phone number and address. And the other class called model.php, which must send the information that the user typed into the MySQL database. However, when a user enters the information in the graphical interface, and then clicks the submit button, the localhost MySQL database is not receiving the data. The name of the database is called “crud”, and the name of the database table inside the crud is called: “gravacoes”.

Please, can anyone help me?

index.php code:

<!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> 

Code of 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>";
                }

            }
        }
    }
}
?>

Advertisement

Answer

You are doing approximately everything right, one thing is not right is that your trying to catch Exception from database connection, and mysqli object do not throw any exceptions by default, so try first to enable error reporting:

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

SQL injection warning:

You should be using prepared statement to insert data to your database to prevent SQL injection like:

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

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

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

$st->execute();

That’s could be enough, but I prefer using PDO for this kind of logic, and also you can separate validation from model, so I made you another implementation, not the best but just to put you on the road:

First your model: it’s the same but would be better if you separate db connection from your model:

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
    }
}

then I added a file that handle your form logic

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);
}

Then in your 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>
          ....
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement