如何使用PDO注册系统将数据插入数据库? [英] How to insert data into database using PDO registry system?

查看:110
本文介绍了如何使用PDO注册系统将数据插入数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我试图创建一个将数据插入我的数据库的注册系统。该页面可以正常使用表单,单击注册按钮后什么都没有发生。

hello im trying to create a registration system that will insert data into my database. The page is all working correctly with the form and all but nothing happens after clicking the register button.

这是来自注册页面的php代码

this is the php code from the register page

<?php
INCLUDE "connect.php";
INCLUDE "errors.php";

session_start();
$_SESSION['message'] = '';

if($_SERVER['REQUEST METHOD'] == 'POST') {
    //make sure passwords match
    if ($_POST['password'] == $_POST['confirmpassword']) {

        $username = $mysqli->real_escape_string($_POST['username']);
        $email = $mysqli->real_escape_string($_POST['email']);
        $password = md5($_POST['password']); //md5 hash password secutiy

        //set session variables to display on welcome page
        $_SESSION['username'] = $username;

        //insert user data into database
        $sql = 
        "INSERT INTO users (username, email, password) "
        . "VALUES ('$username', '$email', '$password')";

        //check if mysql query is successful
        if ($mysqli->query($sql) === true){
            $_SESSION['message'] = "Registration successful!"
            . "Added $username to the database!";
            //redirects the user to the homepage
            header("location: home.php");
        }
        else {
            $_SESSION ['message'] = "User could not be added to the database!";
        }

    }
}
?>

这是connect.php的php代码

and this is the php code from connect.php

<?php
// Create connection
try{
    $connect = new PDO("mysql:host=xxx;dbname=xxx", "xxx", "xxx");

    $connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo 'Database Connected!';
}
catch(PDOException $error)
{
    $error->getMessage();
}

?>


推荐答案

使用预处理语句的示例针对您的特定用例,不包括所有原始变量分配,而是显示了准备,绑定和执行sql语句的基础。

Example of using prepared statements for your particular use-case, does not include all of the original variable assignments but shows the basics of preparing, binding and executing the sql statement.

$dbhost =   'localhost';
$dbuser =   'root';
$dbpwd  =   'xxx';
$dbname =   'xxx';
$db     =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );

$sql='insert into `users` ( `username`, `email`, `password` ) values (?,?,?);';
$stmt=$db->prepare( $sql );

if( $stmt ){
    $stmt->bind_param('sss',$username,$email,$password);
    $result = $stmt->execute();

    $stmt->free_result();
    $stmt->close();
}
$db->close();

if( $result ){
    $_SESSION['message'] = "Registration successful! Added $username to the database!"
} else {
    $_SESSION ['message'] = "User could not be added to the database!";
}

header( "Location: home.php" );

这篇关于如何使用PDO注册系统将数据插入数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆