Not checking for User if existing - php

I want to check if a user exists or not.
It keeps registering users even though I added a check inside. The echo does not give me a accurate feedback on how to fix this issue.
Edit:
Code edited due to comments. It does not exit or check for the existing user.
Here is my code:
if($_POST['username']) {
if ( $password == $c_password ) {
$db_name = '*';
$db_user = '*';
$db_password = '*';
$server_url = '*';
$mysqli = new mysqli($server_url , $db_user, $db_password, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
} else {
$check="SELECT * FROM USER WHERE 'Name'='". $username."'";
$rs = mysqli_query($mysqli,$check) or die(mysqli_error($mysqli));
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
if($data[0] > 1) {
echo "User Already in Exists<br/>";
exit;
}
else
{
$stmt = $mysqli->prepare("INSERT INTO USER (Name, Password) VALUES (?, ?)");
$password = md5($password);
$stmt->bind_param('ss', $username, $password);
/* execute prepared statement */
$stmt->execute();
if ($stmt->error) {error_log("Error: " . $stmt->error); }
$success = $stmt->affected_rows;
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
error_log("Success: $success");
if ($success > 0) {
error_log("User '$username' created.");
echo '{"success":1}';
} else {
echo '{"success":0,"error_message":"Username Exist."}';
}}
}
} else {
echo '{"success":0,"error_message":"Passwords does not match."}';
}
} else {
echo '{"success":0,"error_message":"Invalid Username."}';
}

Related

SQL Login System

I coded this login system, but whenever I try to log in with the only username and password included in my database table, I get redirected to index.php?error=sqlerror. I checked the code for spelling mistakes but there are none. Could this be a problem with the database connection? I use MAMP. I have checked the database and it displays the Success message so it seems to be working. Do you know what I am doing wrong? Thank you!
DATABASE CONNECTION (file name: dbh.inc.php)
$servername = "127.0.0.1";
$dBUsername = "root";
$dBPassword = "";
$dBName = "gallerydatabase";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
if (!$conn) {
echo "Error: Unable to connect to MySQL.";
}
echo "Success";
mysqli_close($conn);
?>
LOG-IN PHP CODE (file name: login.inc.php)
if (isset($_POST['login-submit'])) {
require 'dbh.inc.php';
$mailuid = $_POST['mailuid'];
$password = $_POST['pwd'];
if (empty($mailuid) || empty($password)) {
header ("Location: ../index.php?error=emptyfields");
exit();
}
else {
$sql = "SELECT * FROM users WHERE uidUsers=?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header ("Location: ../index.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "s", $mailuid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$pwdCheck = password_verify($password, $row['pwdUsers']);
if ($pwdCheck == false) {
header ("Location: ../index.php?error=wrongpwd");
exit();
}
else if ($pwdCheck == true) {
session_start();
$_SESSION['userId'] = $row['idUsers'];
$_SESSION['userUid'] = $row['uidUsers'];
header ("Location: ../index.php?login=sucess");
exit();
}
else {
header ("Location: ../index.php?error=wrongpwd");
exit();
}
}
else {
header ("Location: ../index.php?error=nouser");
exit();
}
}
}
}
else {
header ("Location: ../index.php");
exit();
}
I think the problem is in your file dbh.inc.php, you create the connection $conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName); and later you close it as well mysqli_close($conn);.
So by the time you come to use $conn in login.inc.php your connection is closed. What you need to do is write a function in dbh.inc.php that returns a live connection (don't call close), use that to do your DB queries / insert and after that close the connection.
A reusable database class can be written (functional style) as follows
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
trait DBInfo {
protected $servername = "127.0.0.1";
protected $username = "root";
protected $password = "";
protected $dbname = "gallerydatabase";
}
class Database{
use DBInfo;
function __construct() {}
function connection(){
$conn = new mysqli($this->servername, $this->username,
$this->password, $this->dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else{
$conn->autocommit(FALSE);
return $conn;
}
}
function select($sql, $fn2bind_takestmt, $fn2process_row_return_result){
try{
$result = array();
$conn = $this->connection();
$stmt = $conn->prepare($sql);
$fn2bind_takestmt($stmt);
$stmt->execute();
$rowset = $stmt->get_result();
while ($row = $rowset->fetch_assoc()) {
$obj = $fn2process_row_return_result($row);
array_push($result, $obj);
}
}catch(Exception $e) {
$result = NULL;
throw $e;
}finally{
if(isset($rowset))$rowset->close();
if(isset($stmt))$stmt->close();
if(isset($conn))$conn->close();
}
return $result;
}
// You can introduce functions for insert, update and delete as well
}
?>
and then for database selects for example login check
<?php
function allow_login($user, $pwd){
$sql = "SELECT count(*) rec_count FROM users WHERE uidUsers=? and pwdUsers=?"
$db = new Database();
$result = $db->select($sql,
function($stmt) use($user, $pwd){
$stmt->bind_param("ss", $user, $pwd);
},
function($row){
if($row['rec_count'] > 0){// or whatever
return TRUE;
}
return FALSE;
}
);
if(isset($result)){
return $result[0];
}
return $result;
}
?>

My Webpage doesn't recognize the data fulfilled in a registration form

I'm currently doing a webpage, and by now I'm focused on the log in and registration forms. I have also a sql database connected. When I register a new user with the registration form, the database is updated succesfully. The problem is that when I try to log in with that user, the page doesn't recognize it. Besides, if I try to log in with an user that I introduced manually with Netbeans, it recognize it.
$con = mysqli_connect("localhost", "root", "mypassword");
if(!$con) {
exit('Connect Error (' . mysqli_connect_errno() .') ' . mysqli_connect_error());
}
mysqli_set_charset($con, 'utf-8');
mysqli_select_db($con, "my_database");
$user = mysqli_real_escape_string($con, htmlentities($_POST['new_mail']));
$password = mysqli_real_escape_string($con, htmlentities($_POST['new_passwd']));
$sql = "INSERT INTO usuarios (usuario, clave) VALUES ('". $user ."' , ' ".md5($password)."')";
mysqli_query($con, $sql);
if(mysqli_affected_rows($con) > 0) {
?>
<script type='text/javascript'>
alert('You have been registered succesfully. Now you can access our website');
</script>
<?php
header("Location: login_page.html");
echo "<br><br><a href='index.php'>Go back</a>";
} else {
if(mysqli_errno($con) == 1062) {
echo "The e-mail address introduced is already on the system.";
echo "<br><a href='register.html'>Try again</a>";
} else {
echo "Error: " .$sql . "<br>" . mysqli_error($con);
}
}
That's the code I use after fulfilling the registration form. The next one is the one I use after the log in form.
$con = mysqli_connect("localhost", "root", "mypassword");
if(!$con) {
exit('Connect Error (' . mysqli_connect_errno() .') ' . mysqli_connect_error());
}
if(mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_errno());
exit();
}
mysqli_set_charset($con, 'utf-8');
mysqli_select_db($con, "my_database");
$user = mysqli_real_escape_string($con, htmlentities($_POST['username']));
$password = mysqli_real_escape_string($con, htmlentities($_POST['password']));
$sql = "SELECT * FROM usuarios WHERE usuario='" . $user ."' AND clave='" . md5($password) . "'";
mysqli_query($con, $sql);
if(mysqli_affected_rows($con) > 0) {
//echo "Welcome " . $_SESSION['username'] . "!";
//echo "<br><br><a href='user_page.php'>Main Page</a>";
//echo "<br><a href= 'close_session.php'>Close Session</a>";
header("Location: main_page.html");
} else {
exit ("The user or password introduced are not correct");
}
$row = mysqli_fetch_row($sql);
$_SESSION['user'] = $row;
$_SESSION['username'] = $row[0];
mysqli_free_result($sql);
?>
Thank you for your help.
Few mistakes that you are doing on your registration page.
You are not using prepared statements.
You are using md5() instead of password_hash() and password_verify() to secure your passwords.
You are using cleansing mechanism on the password which you should't as this may change the original password.
With the above you should use prepared statements and take the advantage of password hash and verify,
therefore your register page. should look :
<?php
$con = mysqli_connect("localhost", "root", "mypassword");
if (!$con) {
exit('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
mysqli_set_charset($con, 'utf-8');
mysqli_select_db($con, "my_database");
$user = $_POST['new_mail'];
$password = $_POST['new_passwd'];
$hash = password_hash($password, PASSWORD_DEFAULT);
//check if user is not registered already, I'm not sure if you have user_id, what I know you should have id which is auto increment, then select that id
$sql = "SELECT user_id FROM usuarios WHERE usuario = ? ";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 's', $user);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
//user exists
echo "The e-mail address introduced is already on the system.";
echo "<br><a href='register.html'>Try again</a>";
} else {
//user does not exist register the user
$query = "INSERT INTO usuarios (usuario, clave) VALUES (?,?)";
$insert = mysqli_prepare($con, $query);
mysqli_stmt_bind_param($insert, "ss", $user, $hash);
if (mysqli_stmt_execute($insert)):
?>
<script type='text/javascript'>
alert('You have been registered succesfully. Now you can access our website');
</script>
<?php
header("Location: login_page.html");
echo "<br><br><a href='index.php'>Go back</a>";
else:
printf("Error: %s.\n", mysqli_stmt_error($insert));
endif;
}
?>
Then login
<?php
session_start();
$con = mysqli_connect("localhost", "root", "mypassword");
if (!$con) {
exit('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_errno());
exit();
}
mysqli_set_charset($con, 'utf-8');
mysqli_select_db($con, "my_database");
$user = $_POST['username'];
$password = $_POST['password'];
#ONLY SELECT THE SPECIFIC COLUMNS YOU NEED, DON'T USE#
$sql = "SELECT clave,anotherColumn,anotherColumn FROM usuarios WHERE usuario= ? ";
$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, 's', $login);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$row = $row = mysqli_fetch_assoc($result);
if (password_verify($password, $row['clave'])) {
//passwords set sections, redirec
} else {
//user password does not match the stored hash return message
}
} else {
//username does not exist, do something
}
?>

PHP to mySQL check if user exists

I have a script that updates/creates user from an iOS device. Now i want to have the script also check if the user already exists in the database. I am going to restrict this to username for now, so no more than ONE unique username may exist. I have an if-statement in my PHP but i cannot get it to work - help please :).
<?php
header('Content-type: application/json');
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
if($username && $password) {
$db_name = 'dbname';
$db_user = 'dbuser';
$db_password = 'dbpass';
$server_url = 'localhost';
$mysqli = new mysqli('localhost', $db_user, $db_password, $db_name);
$userexists = mysql_query("SELECT * FROM users WHERE username='$username'");
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
}
if(mysql_num_rows($userexists) != 0) {
echo '{"success":0,"error_message":"Username Exist."}';
}
else {
$stmt = $mysqli->prepare("INSERT INTO users (username, password, email) VALUES (?, ?, ?)");
$password = md5($password);
$stmt->bind_param('sss', $username, $password, $email);
/* execute prepared statement */
$stmt->execute();
if ($stmt->error) {error_log("Error: " . $stmt->error); }
$success = $stmt->affected_rows;
/* close statement and connection */
$stmt->close();
/* close connection */
$mysqli->close();
error_log("Success: $success");
if ($success > 0) {
error_log("User '$username' created.");
echo '{"success":1}';
}
else {
echo '{"success":0,"error_message":"Username Exist."}';
}
}
}
else {
echo '{"success":0,"error_message":"Passwords does not match."}';
}
}
else {
echo '{"success":0,"error_message":"Invalid Username."}';
}
}
else {
echo '{"success":0,"error_message":"Invalid Data."}';
}
?>
You could SELECTthe table before trying to insert username. If it already exists (= you have a result) you dont simply insert.
Better yet, use ON DUPLICATE IGNORE or something like that.

Call to a member function execute() on a non-object in

I have the following error, and this is the exact same form processing file I use for registering a user, but I changed it for the appropriate table and columns. While the reg works fine every time.
Here is the code where the error is located:
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (:yas,:yasas,:yasasha)";
$q = $conn->prepare($sql);
$q->execute(array(':yas'=>$eventname,':yasas'=>$about,':yasasha'=>$website));
Here is the full code:
<?php
$servername = "localhost";
$username = "root";
$password = "Af2vaz93j68";
$dbname = "pdo_ret";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$eventname = $_POST['eventname'];
$about = $_POST['about'];
$website = $_POST['website'];
if($eventname == '') {
$errmsg_arr[] = 'You must enter your Email';
$errflag = true;
}
if($about == '') {
$errmsg_arr[] = 'You must enter your Password';
$errflag = true;
}
if($website == '') {
$errmsg_arr[] = 'You must enter First Name';
$errflag = true;
}
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (:yas,:yasas,:yasasha)";
$q = $conn->prepare($sql);
$q->execute(array(':yas'=>$eventname,':yasas'=>$about,':yasasha'=>$website));
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Youre confusing PDO and mysqli. mysqli does not support named parameters so you stmt is not compiling and Mysqli::prepare is returning false. Additionally mysqli does not support passing the param to be bound through mysqli_stmt::execute so even if you switch to positional placeholders your execute will fail.
This is what you would need for mysqli:
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (?,?,?)";
$stmt = $conn->prepare($sql);
// check to make sure the statement was prepared without error
if ($stmt) {
// the statement is good - proceed
$stmt->bind_param('sss', $eventname, $about, $website);
$stmt->execute();
}
Additionally this makes no sense at all:
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
This will just run the same query again either inserting a second row of the exact same data, or perhaps creating a duplicate key error depending upon your schema.
If you want to test that the previous query succeeded you would do something like:
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (?,?,?)";
$stmt = $conn->prepare($sql);
if ($stmt) {
$stmt->bind_param('sss', $eventname, $about, $website);
$success = $stmt->execute();
} else {
$success = false;
}
if ($success === true) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
If you want to use PDO (which i prefer and usually recommend) your code would look something like this:
$conn = PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$sql = "INSERT INTO events1 (eventname,about,website) VALUES (:yas,:yasas,:yasasha)";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':yas'=>$eventname,':yasas'=>$about,':yasasha'=>$website));
echo "New record created successfully";
} catch (PDOException $e) {
echo "Error: " . $sql . "<br>" . $e->getMessage();
}

php login form not working correctly

I'm trying to create a simple login functionality but it's not working, and I'm relatively new to mysqli so please bear with me. I just want to check if the email address and password are correct and if they are then log the user in. Thanks in advance.
Here is my login code that checks the credentials:
UPDATED CODE - I added the report all and I'm now getting internal server error
<?php
require_once 'connect.php';
mysqli_report(MYSQLI_REPORT_ALL);
session_start();
if (!isset($_SESSION['email'])) {
$e = trim($_REQUEST['email']);
$email = $mysqli->real_escape_string($e);
$p = trim($_REQUEST['password']);
$password = $mysqli->real_escape_string($p);
/*
if ($result = $mysqli->query("SELECT email, password, user_id" .
" FROM users" .
" WHERE email = '$email' AND password = '$password'")) {
printf("Select returned %d rows.\n", $result->num_rows);
echo 'Total results: ' . $result->num_rows;
}
*/
if ($stmt = $mysqli->prepare("SELECT email, password, user_id FROM users WHERE email=? AND password=?")) {
/* bind parameters for markers */
$stmt->bind_param("ss", $email, $password);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($email, $password);
/* fetch value */
$stmt->fetch();
if ($stmt->num_rows==1) {
$row = $stmt->fetch_assoc(MYSQLI_NUM);
$user_id = $row['user_id'];
$_SESSION['user_id'] = $user_id;
$_SESSION['email'] = $email;
header("Location: home.php");
/* close statement */
$stmt->close();
} else {
printf("Error message: %s\n", $mysqli->error);
}
/*
if ($result->num_rows==1) {
$row = $result->fetch_assoc(MYSQLI_NUM);
$user_id = $row['user_id'];
if ($query_group = $mysqli->query("SELECT *" .
" FROM user_groups" .
" WHERE user_id = '".$user_id."'")) {
//No more setcookie
$_SESSION['user_id'] = $user_id;
$_SESSION['email'] = $email;
} else {
echo 'Did not work';
}
}
*/
/* free result set */
// $result->close();
}
}
?>
And here is connect.php to connect to the database:
<?php
$mysqli = new mysqli("data", "username", "password", "db");
if($mysqli->connect_errno > 0){
die('Unable to connect to database [' . $mysqli->connect_error . ']');
}
?>
did you try to remove one of the brackets in the end of ypur code. I guess you have to remove one of them.

Categories