简体   繁体   中英

Saving Class to Database in Object Oriented PHP

I'm new to Object Oriented Programming and I don't know if I'm doing it right. I want to take the data from the form submitted and add it to the database. The database credentials are correct.

<?php 

require_once('../layout.php');
require_once('../dbconnect.php');

class student{
    public $f_name;
    public $l_name;
    public $email;
    public $state;
    public $phone;
    public $birthday;
    public function __construct($f_name,$l_name,$email,$state,$phone,$birthday) {
        $f_name  = $_POST['f_name'];
        $l_name  = $_POST['l_name'];
        $email = $_POST['email'];
        $state  = $_POST['state'];
        $phone = $_POST['phone'];
        $birthday = $_POST['birthday'];
        $query = 'INSERT INTO `student`(`first_name`, `last_name`, `email`, `state`, `phone`, `birthday`) VALUES ($f_name,$l_name,$email,$state,$phone,$birthday)';
        $resultquery = mysqli_query($dbconnect,$query);
        if($resultquery) {
            echo "<div class='alert alert-success'>dsf</div>";
        }
    }
}



?>



<form method="post" class="col-md-6 col-md-offset-3">
        <input name="f_name" class="form-control">
        <input name="l_name" class="form-control">
        <input name="email" class="form-control">
        <input name="state" class="form-control">
        <input name="phone" class="form-control">
        <input name="birthday" class="form-control" type="date">
        <input name="submit" type="submit" class="btn btn-default">
</form>

You don't have to pass all the params, because you're declaring them in the __construct as well. I would remove them from the __construct . So without these params you can do something like this:

if(!empty($_POST['submit'])) { new student(); }

You can add this piece below the class declaration and it will catch the post.

Your class will (in my opinion) become something like:

<?php
  class student{

    public function __construct() {
        $f_name  = $_POST['f_name'];
        $l_name  = $_POST['l_name'];
        $email = $_POST['email'];
        $state  = $_POST['state'];
        $phone = $_POST['phone'];
        $birthday = $_POST['birthday'];
        $query = 'INSERT INTO student(`first_name`, `last_name`, `email`, `state`, `phone`, `birthday`) VALUES ($f_name,$l_name,$email,$state,$phone,$birthday)';
        $resultquery = mysqli_query($dbconnect,$query);
        if($resultquery) {
            echo "<div class='alert alert-success'>dsf</div>";
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM