php registration do not push to db issue - php

I've got 2 classes - db.class.php and user.class.php. Within second one I have 2 methods associated with registration - register and registerValidation. db file is responsible for specifying db credentials and initializing connection. I do not really want to pollute my post so I will only give you db code as a link because I don't really think that the problem lays there.
The code of register method and validation method is:
<?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();
}
}
I also have file doRegister.php which is some kind of endpoint for client side:
<?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);
}
When I send http POST request via postman I get 201(created) but when I go to localhost/phpmyadmin after that, there is no new record inside user table in my mysql db. Why?

The register function is definitely returning false on execution of the insert statement. Also it looks like the columns are wrong.
$query = "
INSERT INTO
users(nick, email , password)
VALUES
(?, ?, ?)";
#before returning true or false do a check on execute()
return $stmt->execute() === true ? true : false;
Also before returning the header 201, do a check on the register function to verify that it was true and not false..

Related

Trying to fetch results from a query as a PDO Object in PHP

Problem: so whenever i try to login it returns the following error:
Notice: Trying to get property 'user_id' of non-object in /butler/Classes/users/users.php on line 191
This happens cause the fetch method where I try to retrieve the user_id from the table comes empty, although the fetchColumn() functions shows that 1 row is found in the query.
I already checked the database table and the naming is correct. Also the html form is passing the parameters correctly that why I didn't posted that part of the code.
login page php
if (!empty($_POST['btnLogin'])) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if ($username == "") {
$login_error_message = 'Username field is required!';
} else if ($password == "") {
$login_error_message = 'Password field is required!';
} else {
$user_id = $app->Login($username, $password); // check user login
if($user_id > 0)
{
$_SESSION['user_id'] = $user_id; // Set Session
header("Location: dashboard/layout.php"); // Redirect user to the profile.php
}
else
{
$login_error_message = 'Invalid login details!';
}
}
}
function login
public function Login($username, $pass)
{
try {
$db = DB();
$query = $db->prepare("SELECT user_id FROM start_users WHERE (user_start= :username) AND (psw= :pass) ");
$query->bindParam("username", $username, PDO::PARAM_STR);
//$enc_password = hash('sha256', $password);
$query->bindParam("pass", $pass, PDO::PARAM_STR);
$query->execute();
if ($query->fetchColumn() > 0) {
$result = $query->fetch(PDO::FETCH_OBJ);
echo 'resultado'.$result.' ';
print_r($query->errorInfo());
return $result->user_id;
} else {
return false;
}
} catch (PDOException $e) {
exit($e->getMessage());
}
}
Your call to
if ($query->fetchColumn() > 0) {
is retrieving the row and so the next call to
$result = $query->fetch(PDO::FETCH_OBJ);
is trying to read the another row, which I assume doesn't exist.
You should instead just make the one call
if ($result = $query->fetch(PDO::FETCH_OBJ)) {
I would also suggest the you look into How to use password_hash as your current method is using plain passwords which aren't recommended.

PHP: PDO if user exists check doesn't work

I'm new to PHP, I created User class/object which has a function that checks for user, it returns $stmt->rowCount() but when I check for it in code it just skip it, register the user..
Here is the code:
if(empty($name_err) && empty($email_err) && empty($username_err) && empty($password_err) && empty($confirm_password_err)) {
if($user->doesUserExist($email) === 0) {
$password = password_hash($password, PASSWORD_DEFAULT);
$user->register($username, $name, $email, $password);
} else {
$global_err = "Email is already taken";
}
}
Here is the function from User class:
public function doesUserExist($email) {
$query = "SELECT * FROM users WHERE email = :email";
$stmt = $this->connection->prepare($query);
$stmt->bindParam(':email', $email);
$stmt->execute();
$rowcount = $stmt->rowCount($stmt);
return $rowcount;
}
instead of === in your condition of if($user->doesUserExist($email) === 0) try to change to ==
and then try to change your method like this:
public function doesUserExist($email) {
$query = "SELECT * FROM users WHERE email = '" . $email . "';";
$stmt = $this->connection->prepare($query);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$rowcount = count($stmt->fetchAll());
return $rowcount;
}
You should Try
Call the function
$checkemail=$api->checkuseremail($email);
if($checkemail)
{
echo $mail_check;
}
and define your function like this
public function checkuseremail($email)
{
$db=getDB();
$stmt = $db->prepare("Select id from table_name where email=:email");
$stmt->bindParam("email", $email, PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->rowCount();
if($count)
{
return true;
}
else
{
return false;
}
}
It will return email are already exist or not

PDO: How to make checks

I create this class but i'm newbie in PHP OOP & PDO and i don't know how and where i must to make check to username is valid , email is valid and e.t.c..
This is my code
Class Users {
private $db;
public function __construct(Database $datebase) {
if (!$database instanceOf Database) {
throw new Exeption();
}
$this->db = $datebase;
}
public function userRegistration($username, $password, $email) {
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$regdate = date('d.m.Y');
$query = $this->db->prepare("INSERT INTO `users` (`username`, `password`, `email`, `regdate`) VALUES (?, ?, ?, ?) ");
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->bindValue(3, $email);
$query->bindValue(4, $regdate);
return ($query->execute()) ? true : false ;
}
}
If you want to check something, use Respect/Validation. For example:
$usernameValidator = v::alnum()->noWhitespace()->length(1,15);
$usernameValidator->validate($_POST['username']); //true or false
$passwordValidator = v::alnum()->length(10, null);
$passwordValidator->validate($_POST['password']); //true or false
v::email()->validate($_POST['email']); //true or false
To check if the username or email exist in your database you can use SQL to search the email or username.
$query = $this->db->prepare("SELECT * FROM users WHERE email = ? ");
$query->bindValue(1, $email);
If the query returns a value than the email or username already exist in your database. From there you can show your own validation.
To check check if user or email exist you don't need another class, just add another method called userExist or emailExist and run a query and then check if you get a result.
public function emailExist($email){
$query = $this->db->prepare("SELECT * FROM users WHERE email = ? ");
$query->bindValue(1, $email);
try{
$query->execute();
//use the if statement and $query->rowCount() to check if there is a result
$rows = $query->rowCount();
if($rows === 1){
return true;
} else {
return false;
}
}catch (PDOException $e) {
die($e->getMessage());
}
}

PHP Error: call to a member function bind_param() on a non-object

I have a php script which should connect to a database, check whether a row with the given field exists and, if it exists, update another field of the same row. However, the UPDATE query seems to fail, and I can't see why. I tried to google the problem but couldn't find a working solution. I tried to echo($mysqli->error) but it gave me an empty string.
Here's the code:
<?php
session_start();
include "../config.php";
if(isset($_GET['actionForgot']) && !empty($_GET['restore'])) {
$piva=trim($_GET['restore']);
$mysqli = new mysqlc();
$stmt = $mysqli->prepare("SELECT username,email FROM login WHERE piva = ?");
$stmt->bind_param("s", $piva);
if (!$stmt->execute()) {
trigger_error('The query execution failed; MySQL said ('.$stmt->errno.') '.$stmt->error, E_USER_ERROR);
}
$stmt->bind_result($username, $email);
if($stmt->fetch()) {
$password = generatePassword(10);
$crypPass = MD5($password);
$stmt = $mysqli->prepare("UPDATE login SET password = ? WHERE piva = ?"); //Here's the error!
if(!$stmt->bind_param("ss",$crypPass,$piva)){
echo "fail";
} else if (!$stmt->execute()) {
trigger_error('The query execution failed; MySQL said ('.$stmt->errno.') '.$stmt->error, E_USER_ERROR);
echo "fail";
} else {
sendEmailRestore($username, $password, $email);
echo $email;
}
} else {
echo "nexists";
}
$stmt->close();
}else{
echo "false";
}
?>
P.S. I'm sure the problem is not in config.php because other similar php scripts work just fine.
EDIT: Could it have something to do with the fact I'm using the same variable $stmt for two queries?
I've found the problem! It had something to do with $mysqli being used for two different queries. I have no idea why this should give problems of any kind, but I changed the code to this:
<?php
session_start();
include "../config.php";
if(isset($_GET['actionForgot']) && !empty($_GET['restore'])) {
$piva=trim($_GET['restore']);
$mysqli = new mysqlc();
$stmt = $mysqli->prepare("SELECT username,email FROM login WHERE piva = ?");
$stmt->bind_param("s", $piva);
if (!$stmt->execute()) {
trigger_error('The query execution failed; MySQL said ('.$stmt->errno.') '.$stmt->error, E_USER_ERROR);
}
$stmt->bind_result($username, $email);
if($stmt->fetch()) {
$password = generatePassword(10);
$crypPass = MD5($password);
$mysqli2 = new mysqlc(); //NOTICE THIS LINE
$stmt = $mysqli2->prepare("UPDATE login SET password = ? WHERE piva = ?"); //AND THIS
if(!$stmt->bind_param("ss",$crypPass,$piva)){
echo "fail";
} else if (!$stmt->execute()) {
trigger_error('The query execution failed; MySQL said ('.$stmt->errno.') '.$stmt->error, E_USER_ERROR);
echo "fail";
} else {
sendEmailRestore($username, $password, $email);
echo $email;
}
} else {
echo "nexists";
}
$stmt->close();
}else{
echo "false";
}
?>
and it works just fine.
I'd still like to know why I was doing it wrong, though...

Check if user exists in database

I've made a user class which validates the data passed through the form and then subsequently updates the database table users. I want to add extra functionality such as checking if the username and email exists in the table, I've added a little script however it doesn't seem to be working.
I inserted a duplicated email address and I did not get the error message "email exists" instead I get the success message "1 row inserted":
Am I doing something wrong below? Is there perhaps a better way to approach this?
public function insert() {
if (isset($_POST['submit'])) {
$email = isset($_POST['email']) ? $this->mysqli->real_escape_string($_POST['email']) : '';
$result = $this->mysqli->prepare("SELECT * FROM users WHERE email='".$email."'");
if ($result->num_rows) {
echo "email exisits!";
}
else
{
$stmt = $this->mysqli->prepare("INSERT INTO users (username, password, name, email) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $username, $password, $name, $email); // bind strings to the paramater
//escape the POST data for added protection
$username = isset($_POST['username']) ? $this->mysqli->real_escape_string($_POST['username']) : '';
$cryptedPassword = crypt($_POST['password']);
$password = $this->mysqli->real_escape_string($cryptedPassword);
$name = isset($_POST['name']) ? $this->mysqli->real_escape_string($_POST['name']) : '';
$email = isset($_POST['email']) ? $this->mysqli->real_escape_string($_POST['email']) : '';
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
}
You are using the worst API you ever can choose.
With safeMysql it would be
$exists = $this->db->getOne("SELECT 1 FROM users WHERE email=?s", $_POST['email']);
if ($exists) {
echo "email exisits!";
}
With PDO it is slightly longer but usable
$stmt = $this->db->prepare("SELECT 1 FROM users WHERE email=?");
$stmt->execute(array($_POST['email']));
$exists = $stmt->fetchColumn();
if ($exists)
{
echo "email exisits!";
}
But with raw mysqli you will need a screenful of code only to check if user exists.
So, the whole function using safeMysql would be
public function insert()
{
if (!isset($_POST['submit'])) {
return FALSE;
}
$sql = "SELECT 1 FROM users WHERE email=?s";
$exists = $this->db->getOne($sql, $_POST['email']);
if ($exists)
{
echo "email exisits!";
return FALSE;
}
$sql = "INSERT INTO users SET ?u";
$allowed = array('username', 'name', 'email');
$insert = $this->db->filterArray($_POST, $allowed);
$insert['password'] = crypt($_POST['password']);
$this->db->query($sql, $insert);
return $this->db->afectedRows();
}
you need to use this code after prepare statement
$stmt->execute();
$stmt->store_result();
put this
if ($result->num_rows > 0) {
echo "email exisits!";
}
instead of
if ($result->num_rows) {
echo "email exisits!";
}
First, you are using prepare (great!) but then you are just passing in the value of email, effectively defeating the benefit of prepared statements.
Second, you never execute the query, which is why you don't get anything in num_rows.
public function insert() {
$result = $this->mysqli->prepare("SELECT COUNT(*) FROM users WHERE email=?");
$result->bind_param("s", $_POST['email']);
$result->execute();
$result->bind_result($email_count);
if ($email_count) {
echo "email exisits!";
} else {
# your other logic
From what I can see you're not assigning a value to num_rows prior to testing it with if ($result->num_rows), so it will always be 0

Categories