Error handling checking database with else if for existing email - php

Im stuck with some code. Im pretty new to this.
If the else statement ($uidcheck) returns false it should execute the elseif statement ($emailcheck). See code below.
$username = $_POST['username'];
$email = $_POST['email'];
$pwd = $_POST['pwd'];
if (empty($username)) {
header("Location: ../signup.php?error=empty");
exit();
}
if (empty($email)) {
header("Location: ../signup.php?error=empty");
exit();
}
if (empty($pwd)) {
header("Location: ../signup.php?error=empty");
exit();
} else {
$sql = "SELECT username FROM user WHERE username='$username'";
$result = mysqli_query($conn, $sql);
$uidcheck = mysqli_num_rows($result);
if ($uidcheck > 0) {
header("Location: ../signup.php?error=username");
exit();
} elseif ($uidcheck < 0) {
$sql = "SELECT email FROM user WHERE email='$email'";
$result = mysqli_query($conn, $sql);
$emailcheck = mysqli_num_rows($result);
if ($emailcheck > 0) {
header("Location: ../signup.php?error=email");
exit();
} else {
$sql = "INSERT INTO user (username, email, pwd)
VALUES ('$username', '$email', '$pwd')";
$result = mysqli_query($conn, $sql);
header("Location: ../index.php");
}
}
}
When the emailadress already exists in the database it should exit and add a parameter to the header.
Thanks in advance!
Sven

Your code may does the purpose. But that is not good enough to read/debug.
if( !isset($_POST["username"]) || !isset($_POST["email"]) || !isset($_POST["pwd"]) || empty($_POST["username"]) || empty($_POST["email"]) || empty($_POST["pwd"]) )
{
header("Location: ../signup.php?error=empty");
exit();
}
$sql = "SELECT username FROM user WHERE username='".mysqli_real_escape_string($username)."'";
$result = mysqli_query($conn, $sql);
$uidcheck = mysqli_num_rows($result);
if ($uidcheck > 0)
{
header("Location: ../signup.php?error=username");
exit();
}
else
{
$sql = "SELECT email FROM user WHERE email='".mysqli_real_escape_string($email)."'";
$result = mysqli_query($conn, $sql);
$emailcheck = mysqli_num_rows($result);
if ($emailcheck > 0) {
header("Location: ../signup.php?error=email");
exit();
}
else {
$sql = "INSERT INTO user (username, email, pwd)
VALUES ('$username', '$email', '$pwd')";
$result = mysqli_query($conn, $sql);
header("Location: ../index.php");
}
}
Here are my Recommendations:
Always check if an variable is declared in the scope using isset() function. If the value of "username" or "email or "pwd" is not submitted in the POST request, your code will throw a Fatal Exception and rendering stops there.....
Don't put the value submitted by the User directly into the SQL query....This will make your web application Vulnerable to SQL Injection Attack.

Try this..
You are checking the MySQL resulted value in a wrong manner. For Example Email is already existed in you DB then your Query results Value, then you don not check with < or > just try with either it is empty or not.
$username = $_POST['username'];
$email = $_POST['email'];
$pwd = $_POST['pwd'];
if (empty($username)) {
header("Location: ../signup.php?error=empty");
exit();
}
if (empty($email)) {
header("Location: ../signup.php?error=empty");
exit();
}
if (empty($pwd)) {
header("Location: ../signup.php?error=empty");
exit();
} else {
echo "Username check";
$sql = "SELECT username FROM user WHERE username='$username'";
$result = mysqli_query($conn, $sql);
$uidcheck = mysqli_num_rows($result);
if (!empty($uidcheck)) {
header("Location: ../signup.php?error=username");
exit();
} elseif (empty($uidcheck)) {
$sql = "SELECT email FROM user WHERE email='$email'";
$result = mysqli_query($conn, $sql);
echo $emailcheck = mysqli_num_rows($result);
if (!empty($emailcheck)) {
header("Location: ../signup.php?error=email");
exit();
} else {
echo "asdasd";
$sql = "INSERT INTO user (username, email, pwd)
VALUES ('$username', '$email', '$pwd')";
$result = mysqli_query($conn, $sql);
header("Location: ../index.php");
}
}
}

Related

Checking if an email exists in another table [duplicate]

This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 2 years ago.
I'm doing an registration form and I'm trying to check if the email that the person inserts in the input is already in another table that has all emails that I allow to be registered. If it is it should register the person. I don't understand where I'm failing. I'm starting now with php. Please help.
<?php
if(isset($_POST['signup-submit'])){
require 'dbh.inc.php';
$username = mysqli_real_escape_string($conn, $_POST['uid']);
$email = mysqli_real_escape_string($conn,$_POST['mail']);
$password = mysqli_real_escape_string($conn,$_POST['pwd']);
$passwordRepeat = mysqli_real_escape_string($conn, $_POST['pwd-repeat']);
$check1 = $_POST['check1'];
$check2 = $_POST['check2'];
if(empty($username) || empty($email) || empty($password) || empty($passwordRepeat)) {
header ("Location: ../header.php?error=emptyfields&uid=".$username."&mail=".$email);
exit();
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match("/^[a-zA-z0-9]*$/", $username)){
header("Location: ../header.php?error=invalidadmail&uid=");
exit();
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
header("Location: ../header.php?error=invalidadmail&uid=".$username);
exit();
}
else if (!preg_match("/^[a-zA-z0-9]*$/", $username)){
header("Location: ../header.php?error=invalidaduid&mail=".$email);
exit();
}
elseif($password !== $passwordRepeat){
header("Location: ../header.php?error=passwordcheck&uid=".$username."&mail=".$email);
exit();
}
elseif((!isset($check1)) || (!isset($check2))){
echo"<script>alert('É necessário confirmar as duas opções :(');
window.location.href='../header.php'</script>";
exit();
}
This is the part of the code that is not working
$sql2 = "SELECT * FROM emails WHERE (email_socio = '$email')";
$res = mysqli_query($conn, $sql2);
if (mysqli_num_rows($res) < 0) {
echo "FAIL";
}
These are other validations and where it will insert the data into final table
else{
$sql = "SELECT uidUsers FROM users WHERE uidUsers=?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
header("Location: ../header.php?error=sqlerror");
exit();
}
else{
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$resultCheck = mysqli_stmt_num_rows($stmt);
if($resultCheck > 0){
header("Location: ../header.php?error=usertaken&mail=".$email);
exit();
}
else {
$sql = "INSERT INTO users (uidUsers, emailUsers, pwdUsers) VALUES (?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
header("Location: ../header.php?error=sqlerror");
exit();
} else {
$hashedPwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "sss", $username, $email, $hashedPwd);
mysqli_stmt_execute($stmt);
$sql ="SELECT * FROM users WHERE uidUsers='$username' AND emailUsers='$email'";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
$userid = $row['idUsers'];
$sql = "INSERT INTO profileimg (userid, status) VALUES ('$userid', 1)";
mysqli_query($conn, $sql);
}
}
header("Location: ../header.php?signup=success");
exit();
}
}
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
else {
header("Location: ../header.php");
exit();
}
Your condition is wrong:
if (mysqli_num_rows($res) < 0) {
echo "FAIL";
}
You're checking for less than zero, when in fact it should be less than one.
So, change it to either of the two:
if (mysqli_num_rows($res) === 0) // it logically cannot contain negative values
if (mysqli_num_rows($res) < 1)

PHP Registration form error on 13th line [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 4 years ago.
i've been trying to fix this error past 4 hours now, and i lost my hopes to do it on my own, so i've getting this error:
Parse error: syntax error, unexpected '||' (T_BOOLEAN_OR) in D:\xampp\htdocs\Login system\includes\signup.inc.php on line 13
How to get it fixed? I overlooked everywhere cuz i knew somewhere could be some left unclosed brackets.
And heres my php code, HELP ALLERT :<
<?php
if (isset($_POST['submit'])) {
include_once 'dbh.inc.php';
$uid = mysqli_real_escape_string($conn, $_POST['uid']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
//Error Handlers
//check for empty fields
if (empty($uid) || empty(email) || empty($pwd)) {
header("Location: ../signup.php?signup=empty");
exit();
} else {
//Check if input characters are valid
if (!preg_match("/^[a-zA-Z*$/]", $uid)) {
header("Location: ../signup.php?signup=empty");
exit();
} else {
//Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
header("Location: ../signup.php?signup=empty");
exit();
} else {
$sql = "SELECT * FROM users WHERE user_uid='$uid'";
$result = mysql_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0) {
header("Location: ../signup.php?signup=usertaken");
exit();
} else {
//Haching the password
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
//Insert the user into the database
$sql = "INSERT INTO users (user_email, user_uid, user_pwd)
VALUES ('$uid', '$email', '$hashedPwd' );";
$result = mysqli_query($conn, $sql);
header("Location: ../signup.php?signup=success");
exit();
}
}
}
} else {
header("Location: ../signup.php");
exit();
}
You're writing the if-else statements the wrong way, the error you're getting is from the if statement with no opening and closing curly brackets, same goes for the other ones.
try this one:
<?php
include_once 'dbh.inc.php';
if (!isset($_POST['submit'])) {
header("Location: ../signup.php");
exit();
}
$uid = mysqli_real_escape_string($conn, $_POST['uid']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
//Error Handlers
//check for empty fields
if (empty($uid) || empty(email) || empty($pwd)) {
header("Location: ../signup.php?signup=empty");
exit();
}
if (!preg_match("/^[a-zA-Z*$/]", $uid)) {
header("Location: ../signup.php?signup=empty");
exit();
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
header("Location: ../signup.php?signup=empty");
exit();
}
if($resultCheck > 0) {
header("Location: ../signup.php?signup=usertaken");
exit();
}
$sql = "SELECT * FROM users WHERE user_uid='$uid'";
$result = mysql_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0) {
header("Location: ../signup.php?signup=usertaken");
exit();
}
//Haching the password
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
//Insert the user into the database
$sql = "INSERT INTO users (user_email, user_uid, user_pwd) VALUES ('$uid', '$email', '$hashedPwd' );";
$result = mysqli_query($conn, $sql);
header("Location: ../signup.php?signup=success");
exit();

Checking if users exists

I did a lot of googling and tried many methods but checking for username existence in Mysqli database is not working. Everything is correct but still the user is getting registered even if there is a username in Database. Please help...My php version is 7 and phpmyadmin is 5.6. My code :-
<?php
session_start();
if (isset($_SESSION['id'])) {
header('Location: user.php');
die();
}
else {
if($_POST['submit']){
$username = strip_tags($_POST['username']);
$email = strip_tags($_POST['email']);
$password = strip_tags($_POST['password']);
$passhash = hash('sha512', $password);
$passhash2 = hash('sha512', $passhash);
$strlen = strlen("$password");
if ($strlen < 10) { {
$lesspass = "Use password of atleast 10 letters";
}
}
else {
$date = date("Y-m-d");
require ('setup.php');
$conn = new mysqli($localhost, $hostuser, $hostpass, $hostdb) or die("conn died");
$query1 = "SELECT * FROM member WHERE username = '$username'";
$result1 = mysqli_query($conn, $query1);
if (mysqli_num_rows($query1) > 0) {
die ("Username in use");
}
else {
$query2 = "SELECT from member WHERE email = $email";
$result2 = mysqli_query($conn, $query2);
if (($result2) > 0) {
$ee = "Email already exists";
}
else {
$query = "INSERT INTO member(username, password, registered, email, activated, status) VALUES('$username', '$passhash2', '$date', '$email', '1', '0')";
$result = mysqli_query($conn, $query);
if($result) {
header('Location: login.php');
}
else {
echo "There was a problem while connecting";
}
}
}
}
}
}
?>
I think the error is that you use mysqli_num_rows on the query string. Do it on the result:
if (mysqli_num_rows($result1) > 0) {
Also, you should take care about SQL injections (escape or use prepared statements), but that's another story. Not sure if strip_tags is sufficient.

Why is PHP sql code not inserting into database, trying to make register

<?php
require_once("db_credentials.php");
$conn = mysqli_connect("localhost", "root", "isdc3333", "collab_schema");
if (isset($_POST["submit"])) {
$first = mysqli_real_escape_string($conn, $_POST["first"]);
$last = mysqli_real_escape_string($conn, $_POST["last"]);
$email = mysqli_real_escape_string($conn, $_POST["email"]);
$uid = mysqli_real_escape_string($conn, $_POST["uid"]);
$pwd = mysqli_real_escape_string($conn, $_POST["pwd"]);
if (empty($first) or empty($last) or empty($email) or empty($uid) or
empty($pwd)) {
header("Location: signup.php?signup=empty");
exit();
} else {
if (!preg_match("/^[a-zA-Z]*$/", $first) or !preg_match("/^[a-zA-
Z]*$/", $last)) {
header("Location: signup.php?signup=invalid");
exit();
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: signup.php");
exit();
} else {
$sql = "SELECT * FROM users WHERE uid='$uid'";
$result = mysqli_query($conn, $sql);
$queryResults = mysqli_num_rows($result);
if ($queryResults > 0) {
header("Location: signup.php?signup=usertaken");
exit();
} else {
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
$sql = "INSERT INTO collab_schema.users (first, last, email, uid,
pwd) VALUES ('$first', '$last', '$email', '$uid',
'$hashedPwd');";
$result = mysqli_query($conn, $sql);
header("Location: signup.php?signup=success");
exit();
}
}
}
}
} else {
header("Location: signup.php");
exit();
echo "Redirecting...";
}
?>
The last sql query won't work, can you list the errors?
Doesn't look like the code is working, but everyone says it fine.
I'm just putting more text because stack overflow says to put more details even when I don't want too :^)

Session login/logout ASP to PHP

I'm just a beginner in PHP. I'm making a website, and it needs to store the time for login and logout of every user. I found this code for it but it's in ASP.
I tried to make it into PHP but I'm unknowledgeable what will I put in the INSERT INTO of sessionid and logintime.
Table name: userlogtime
logid, userid, sessionid, logintime, logouttime, offline
Here's my code:
<?php
if(isset($_POST['submit'])) {
include 'dbheader.php';
$username = mysqli_real_escape_string($conn, $_POST['uname']);
$password = mysqli_real_escape_string($conn, $_POST['pwd']);
//Error handlers
//Check if inputs are empty
if(empty($username) || empty($password)) {
echo '<script type="text/javascript">alert("Please fill out the following");
window.history.back();
</script>';
exit();
} else {
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck < 1) {
echo '<script type="text/javascript">alert("Login error");
window.history.back();
</script>';
//set the user id value from the Members table in a session variable
$_SESSION('member') = $row($userid);
$sql ="UPDATE userlogtime SET offline=True WHERE offline=False AND userid="$_SESSION('member')"";
$sql = "INSERT INTO userlogtime (userid, sessionid, logintime) VALUES ('$_SESSION('member'), );";
exit();
} else {
if ($row = mysqli_fetch_assoc($result)) {
//De-hashing the password
$hashedPwdCheck = password_verify($password, $row['password']);
if ($hashedPwdCheck == false) {
echo '<script type="text/javascript">alert("Login error");
window.history.back();
</script>';
exit();
} elseif($hashedPwdCheck == true) {
$_SESSION['username'] = $row['username'];
$_SESSION['firstname'] = $row['firstname'];
$_SESSION['role'] = $row['Role'];
$_SESSION['image'] = $row['image'];
if($_SESSION['role'] == "User"){
header("Location: user.php");
exit();
}
}
}
}
}
} else {
header("Location: user.php?login=error");
exit();
}
$sql = "INSERT INTO userlogtime (userid, sessionid, logintime) VALUES ('$_SESSION('member'), ".session_id().",now());";

Categories