这是使用oop php准备插入语句的正确方法吗?

时间:2016-07-07 22:41:30

标签: php oop

大家好我已经写了这个注册页面脚本,我想将用户信息注册到数据库中但是我试图通过使用带有oop语法的预备插入语句来安全地执行此操作但不确定我是否正确执行此操作因为当我注册虚拟数据,它不会在数据库中放任何东西。

index.php page

    <!DOCTYPE html>
    <html>
    <head>
    <title>Registration form</title>
    <link rel="stylesheet" type="text/css" href="regisform.css">
    </head>
    <body>
        <div id="form">
        <div id="header"><h2>Registration Form</h2></div>
            <form method="post" action="process.php">
                <label>Username:</label>
                <input type="text" name="username" placeholder="Enter a Username please" required="required" />
                <label>Email:</label>
                <input type="text" name="email" placeholder="Enter your email please" required="required" />
                <label>Password:</label>
                <input type="text" name="password" placeholder="Enter a Password please" required="required" />
                <input type="submit" name="signup" value="Sign up"/>
            </form>
        </div>
    </body>

    </html>

    <?php 
    include "process.php";
       $db = new db();
    if(isset($_POST['signup'])) {
       $user = $_POST['username'];
       $email = $_POST['email'];
       $password = $_POST['password'];

       $query = "INSERT INTO users (user_name, user_email, user_pass) VALUES (?, ?, ?)";

       $run = $db->insert($query);
       $run->bind_param('sss', $user, $email, $password);
       $run->execute();
       $run->close();
    }
?>

process.php页面

<?php

class db {
    public $host = "localhost";
    public $user = "root";
    public $pass = "";
    public $db_name = "pros";

    public $link;

    public function __construct(){
        $this->connect();
    }

    private function connect() {
        $this->link = new mysqli($this->host, $this->user, $this->pass, $this->db_name);
    }

    public function insert ($query) {
        $result = $this->link->prepare($query);
        if($result){
            echo "<center><h2>Registration Successfull!</h2></center>";
        }
        else
        {
            echo "<center><h2>Registration failed!</h2></center>";
        }
      return $result;
    }
}

?>

1 个答案:

答案 0 :(得分:2)

我会使用一个函数或方法来完成所有插入

public function insert_new_user($username, $email, $password){

    $mysqli = $this->link;

    $sql = "INSERT INTO users"
        . " (user_name, user_email, user_pass)"
        . " VALUES (?, ?, ?)";

    $stmt = $mysqli->prepare( $sql );

    $stmt->bind_param("sss", $username, $email, $password );

    if($stmt->execute()){
        return "success";
    } else {
        return "failed: " . $mysqli->error;
    }

}