问题
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.
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!";
}
}
}
?>
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();
}
?>
回答1:
The first order of business is to connect to MySQL using the PDO object.
I have created a file called connect.php
<?php
//connect.php
//Our MySQL user account.
define('MYSQL_USER', 'root');
//Our MySQL password.
define('MYSQL_PASSWORD', '');
//The server that MySQL is located on.
define('MYSQL_HOST', 'localhost');
//The name of our database.
define('MYSQL_DATABASE', 'test');
/**
* PDO options / configuration details.
* I'm going to set the error mode to "Exceptions".
* I'm also going to turn off emulated prepared statements.
*/
$pdoOptions = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
);
/**
* Connect to MySQL and instantiate the PDO object.
*/
$pdo = new PDO(
"mysql:host=" . MYSQL_HOST . ";dbname=" . MYSQL_DATABASE, //DSN
MYSQL_USER, //Username
MYSQL_PASSWORD, //Password
$pdoOptions //Options
);
//The PDO object can now be used to query MySQL.
User Registration Form
<?php
//register.php
/**
* Start the session.
*/
session_start();
/**
* Include ircmaxell's password_compat library.
*/
require 'lib/password.php';
/**
* Include our MySQL connection.
*/
require 'connect.php';
//If the POST var "register" exists (our submit button), then we can
//assume that the user has submitted the registration form.
if(isset($_POST['register'])){
//Retrieve the field values from our registration form.
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
//TO ADD: Error checking (username characters, password length, etc).
//Basically, you will need to add your own error checking BEFORE
//the prepared statement is built and executed.
//Now, we need to check if the supplied username already exists.
//Construct the SQL statement and prepare it.
$sql = "SELECT COUNT(username) AS num FROM users WHERE username = :username";
$stmt = $pdo->prepare($sql);
//Bind the provided username to our prepared statement.
$stmt->bindValue(':username', $username);
//Execute.
$stmt->execute();
//Fetch the row.
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//If the provided username already exists - display error.
//TO ADD - Your own method of handling this error. For example purposes,
//I'm just going to kill the script completely, as error handling is outside
//the scope of this tutorial.
if($row['num'] > 0){
die('That username already exists!');
}
//Hash the password as we do NOT want to store our passwords in plain text.
$passwordHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
//Prepare our INSERT statement.
//Remember: We are inserting a new row into our users table.
$sql = "INSERT INTO users (username, password) VALUES (:username, :password)";
$stmt = $pdo->prepare($sql);
//Bind our variables.
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passwordHash);
//Execute the statement and insert the new account.
$result = $stmt->execute();
//If the signup process is successful.
if($result){
//What you do here is up to you!
echo 'Thank you for registering with our website.';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Register</title>
</head>
<body>
<h1>Register</h1>
<form action="register.php" method="post">
<label for="username">Username</label>
<input type="text" id="username" name="username"><br>
<label for="password">Password</label>
<input type="text" id="password" name="password"><br>
<input type="submit" name="register" value="Register"></button>
</form>
</body>
</html>
回答2:
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" );
来源:https://stackoverflow.com/questions/44470690/how-to-insert-data-into-database-using-pdo-registry-system