这是在OOP php中使用准备好的INSERT语句的正确方式吗?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (13)

你好,我已经编写了这个注册页面脚本,我想将用户信息注册到数据库中,但是我试图通过使用带有OOP语法的预准备INSERT语句来安全地完成这个任务,但不确定是否正确,因为当我注册虚拟数据时,它不会在数据库中放置任何内容。

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 page

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

?>
提问于
用户回答回答于

我将使用一个函数或方法来执行所有的插入。

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

}

扫码关注云+社区

领取腾讯云代金券