我有2个课程 - db.class.php
和user.class.php
。在第二个方面,我有2个与注册相关的方法 - register
和registerValidation
。 db
文件负责指定数据库凭据和初始化连接。我真的不想污染我的帖子所以我只会给你一个link的db代码,因为我真的不认为问题就在那里。
register
方法和validation
方法的代码是:
<?php
require_once 'token.php';
class User
{
//db and table name
private $conn;
private $table_name = "users";
// constructor with $db as database connection
public function __construct($db)
{
$this->conn = $db;
}
public function registerValidation($nick,$email,$password)
{
if(
(strlen($nick) < 5 || strlen($nick) > 20) ||
(strlen($email) < 3 || strlen($email) > 100) ||
(strlen($password) < 6 || strlen($password) > 50)
)
{
//$error = 'nick or email or password is wrong length';
//echo json_encode($error);
return false;
}
else
{
// query to check if email already exists
$query = "
SELECT
*
FROM
" . $this->table_name . "
WHERE
id = ?
OR
email = ?
";
// prepare query statement
$stmt = $this->conn->prepare($query);
// bind params
$stmt->bindParam(1, $nick);
$stmt->bindParam(2, $email);
// execute query
$stmt->execute();
//count if there is same
$num = $stmt->rowCount();
if ($num > 0)
{
return false;
}
else
{
return true;
}
}
}
public function register($nick,$email,$password)
{
try
{
$password = password_hash($password, PASSWORD_DEFAULT);
$query = "
INSERT INTO
users(user, user, user)
VALUES
(?, ?, ?)";
// prepare query statement
$stmt = $this->conn->prepare($query);
//bind values from user
$stmt->bindparam(1, $nick);
$stmt->bindparam(2, $email);
$stmt->bindparam(3, $password);
$stmt->execute();
return $stmt;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
我还有文件doRegister.php
,它是客户端的某种端点:
<?php
if(isset($_POST['submit']))
{
if(!empty($_POST['nick'])
&& !empty($_POST['email'])
&& !empty($_POST['password']))
{
// instantiate database
require_once '../config/database.php';
$database = new Database();
$db = $database->getConnection();
require_once '../classes/user.php';
$user = new User($db);
if($user->registerValidation($_POST['nick'], $_POST['email'], $_POST['password']))
{
$user->register($_POST['nick'], $_POST['email'], $_POST['password']);
http_response_code(201);
}
else
{
http_response_code(400);
}
}
else
{
http_response_code(400);
}
}
else
{
http_response_code(400);
}
当我通过邮递员发送http POST请求时,我得到201(created)
但是当我转到localhost/phpmyadmin
之后,我的mysql数据库中的用户表中没有新记录。为什么呢?
答案 0 :(得分:1)
register
函数在执行insert
语句时肯定会返回false。它看起来像列是错误的。
$query = "
INSERT INTO
users(nick, email , password)
VALUES
(?, ?, ?)";
#before returning true or false do a check on execute()
return $stmt->execute() === true ? true : false;
在返回标题201之前,请检查register
函数以验证它是否为真,而不是错误。