If else statement error confused - php

Hello guys I was confused using the if else statement I know it is the basic in conditioning also other languages. Don't know what to do here, I would like that it has an if condition(check) then also inside I want that it has an else if but my problem is I have to else statement which is wrong cause I know that else statement will be use at the end of a condition
Here's my code:
if (isset($_POST['login']))
{
$idno = mysql_real_escape_string($_POST['idno']);
$password = mysql_real_escape_string($_POST['password']);
$position = $_POST['user_type'];
$YearNow=Date('Y');
$_SESSION['SESS_MEMBER_ID'] = $idno;
$sql1 = "SELECT * FROM student WHERE idno = '$idno' AND password = '$password' " ;
$result = mysql_query($sql1) or die();
$row = mysql_fetch_array($result);
$num_row = mysql_num_rows($result);
//,student WHERE studentvotes.idno = student.idno
$sql2 = "SELECT * FROM vote_logs,school_year where vote_logs.idno='$idno' AND vote_logs.syearid = school_year.syearid AND school_year.from_year like $YearNow ";
$result1 = mysql_query($sql2) or die();
$row1 = mysql_fetch_array($result1);
if (mysql_num_rows($result1)<=1)
{
$_SESSION['idno']=$row['idno'];
$sql_c = "SELECT * FROM student WHERE idno = '$idno' AND password = '$password'";
$result2 = mysql_query($sql_c) or die(mysql_error());
$faunc = mysql_fetch_assoc($result2);
$_SESSION['SESS_COURSE'] = $faunc['progid'];
$_SESSION['SESS_MEMBER_ID'] = $idno;
header('location: plsvote.php');
}
else if ($row['status'] == 'lock')
{
header('location: last.php');
}
else
{
header('location: notification.php');
exit();
}
else
{
echo "<script type='text/javascript'>\n";
echo "alert('Username or Password incorrect!, Please try again.');\n";
echo "window.location = 'index.php';";
echo "</script>";
exit();
}
}
Please help me

You have imbricated your blocks, try this:
if (isset($_POST['login']))
{
$idno = mysql_real_escape_string($_POST['idno']);
$password = mysql_real_escape_string($_POST['password']);
$position = $_POST['user_type'];
$YearNow=Date('Y');
$_SESSION['SESS_MEMBER_ID'] = $idno;
$sql1 = "SELECT * FROM student WHERE idno = '$idno' AND password = '$password' " ;
$result = mysql_query($sql1) or die();
$row = mysql_fetch_array($result);
$num_row = mysql_num_rows($result);
//,student WHERE studentvotes.idno = student.idno
$sql2 = "SELECT * FROM vote_logs,school_year where vote_logs.idno='$idno' AND vote_logs.syearid = school_year.syearid AND school_year.from_year like $YearNow ";
$result1 = mysql_query($sql2) or die();
$row1 = mysql_fetch_array($result1);
if (mysql_num_rows($result1)<=1)
{
$_SESSION['idno']=$row['idno'];
$sql_c = "SELECT * FROM student WHERE idno = '$idno' AND password = '$password'";
$result2 = mysql_query($sql_c) or die(mysql_error());
$faunc = mysql_fetch_assoc($result2);
$_SESSION['SESS_COURSE'] = $faunc['progid'];
$_SESSION['SESS_MEMBER_ID'] = $idno;
header('location: plsvote.php');
}
else if ($row['status'] == 'lock')
{
header('location: last.php');
}
else
{
header('location: notification.php');
exit();
}
}
else
{
echo "<script type='text/javascript'>\n";
echo "alert('Username or Password incorrect!, Please try again.');\n";
echo "window.location = 'index.php';";
echo "</script>";
exit();
}
With an indentation, this kind of problem is easily visible.

This can be ok:
if ( //validate the email
filter_var($email, FILTER_VALIDATE_EMAIL) &&
preg_match('/#.+\./', $email)
) {
$result = mysql_query (
"INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())"
);
if ($result) { // check for successful store
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
// return user details
return mysql_fetch_array($result);
} else {
return false; //unsuccessful store
}
} else {
//not a valid email
return false;
}
}

Try this one :
if (filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/#.+\./', $email)) {
$result = mysql_query ("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())");
if ($result) { // check for successful store
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM users WHERE uid = $uid");
// return user details
return mysql_fetch_array($result);
} else {
return false; //unsuccessful store
}
} else {
//not a valid email
return false;
}

Related

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.

Error handling checking database with else if for existing email

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");
}
}
}

password_verify stops working after changing hash

I'm working on implementing the ability for users to edit their passwords.
I'm using PASSWORD_BYCRYPT, and password_verify works fine after creating a user, but as soon as a user edits their password, it stops working.
Password change:
else if (isset($_POST["submitUpdateSettingsPW"])) {
$passwordText = $_POST["passwordChangeInput"];
$userID = $_SESSION["userID"];
$passwordNew = password_hash($passwordText, PASSWORD_BCRYPT);
$sql = "UPDATE users SET password = '$passwordNew' WHERE id = '$userID';";
if (mysqli_query($conn, $sql)) {
header("location: settings.php");
}
else {
header("location: settings.php?message=Something+went+wrong.+You+may+not+have+the+permissions+to+do+this.");
}
}
Password creation
else if (isset($_POST["submitSignup"])) {
$email = mysqli_real_escape_string($conn, $_POST["emailInput"]);
$passwordText = $_POST["passwordInput"];
$password = password_hash($passwordText, PASSWORD_BCRYPT);
$signupSQLCheck = "SELECT * FROM users WHERE email = '$email'";
$result = mysqli_query($conn, $signupSQLCheck);
if (mysqli_num_rows($result) == 0) {
$signupSQL = "INSERT INTO users set email = '$email', password = '$password'";
mysqli_query($conn, $signupSQL);
header("location: login.php?message=Your+account+is+active.+You+may+now+login.");
}
else {
header("location: login.php?message=This+email+is+already+registered.+Do+you+want+to+<a href = 'login.php'>login</a>?");
}
}
Password verify (works fine until changing password)
if (isset($_POST["submitLogin"])) {
$email = mysqli_real_escape_string($conn, $_POST["emailInput"]);
$passwordText = $_POST["passwordInput"];
$loginSQL = "SELECT * FROM users WHERE email = '$email' LIMIT 1";
$result = mysqli_query($conn, $loginSQL);
if (mysqli_num_rows($result) == 1) {
$row = mysqli_fetch_assoc($result);
$hash = $row["password"];
if (password_verify($passwordText, $hash)) {
$_SESSION["user"] = 1;
$_SESSION["userID"] = $row["id"];
header("location: index.php");
}
}
else {
header("location: login.php?message=Incorrect+email+or+password.+Do+you+want+to+<a href = 'signup.php'>sign up</a>?");
}
}
Thanks in advance

Why is my user being added to one table but not another

I am creating a profile image upload system for my users. Upon signup, the php code should create a user in the table "user" and also create a user in the "profileImg" table. I am getting no errors in my log but the user is being added to "user" but not "profileImg". Can anyone please assist. Thank you in advance.
SIGNUP.INC.PHP:
<?php
session_start();
include '../dbh.php';
$respond = array(
'status' => true,
'message' => 'There was an error',
'redirect' => '../profile.php',
'errors',
);
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']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$errorEmpty = false;
$errorEmail = false;
if (empty($first) || empty($last) || empty($email) || empty($pwd)) {
$respond['errors'][] = "Please fill out all fields!";
$respond['errorEmpty'] = true;
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$respond['errors'][] = "Please enter a valid email address!";
$respond['errorEmail'] = true;
} else {
$sql = "SELECT email FROM user WHERE email='$email'";
$result = mysqli_query($conn, $sql);
$emailcheck = mysqli_num_rows($result);
if ($emailcheck > 0) {
$respond['errors'][] = "That email address already exists!";
$respond['errorEmail'] = true;
}
else {
$encryptpwd = password_hash($pwd, PASSWORD_DEFAULT);
$sql = "INSERT INTO user (first, last, email, pwd)
VALUES ('$first', '$last', '$email', '$encryptpwd')";
$result = mysqli_query($conn, $sql);
$sql = "SELECT * FROM user WHERE email='$email' AND first='$first'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$email = $row['id'];
$sql = "INSERT INTO profileImg (email, status)
VALUES ('$email', 1)";
}
}
}
}
}
echo json_encode($respond);
?>
PROFILE.PHP:
This must be a violation on database level.
See this block of yours:
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$email = $row['id'];
$sqlProfile = "INSERT INTO profileImg (email, status)
VALUES ('$email', 1)";
}
}
I'm pretty sure that in your database the email column of profileImg table is a varchar, although you are inserting it as an int $email = $row['id'];
Replace that line by the this $email = $row['email'];
Code after changes:
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$email = $row['email'];
$sqlProfile = "INSERT INTO profileImg (email, status)
VALUES ('$email', 1)";
mysqli_query($conn, $sqlProfile);
}
}
Update: add mysqli_query($conn, $sqlProfile); to execute the query

What should i do php

I think I have an error uon the usertype 3 cause it always go to the notification and if I change both notification and plsvote.php it will just refresh so please help me what to do
if (isset($_POST['login'])){
$idno = $_POST['idno'];
$password = $_POST['password'];
$position = $_POST['user_type'];
$sql1 = "SELECT * FROM users WHERE idno = '$idno' AND password = '$password'";
$result = mysql_query($sql1) or die();
$row = mysql_fetch_array($result);
$num_row = mysql_num_rows($result);
//if the user is admin
if ($row['user_type'] == "1"){
mysql_query("insert into user_log (idno,login_date) values('$username',NOW())")or die(mysql_error());
$YearNow=Date('Y');
header('location:admin/index.php');
}
//if the user is student
else if ($row['user_type'] == "3") {
$sql_c = "SELECT * FROM users,studentvotes,school_year = users.idno = studentvotes.idno AND studentvotes.syearid =school_year.syearid AND school_year.from_year like $YearNow ";
$result1 = mysql_query($sql_c) or die(mysql_error());
while($row2=mysql_fetch_array($result1)){
$_SESSION['SESS_COURSE'] = $row2['progid'];
$_SESSION['SESS_MEMBER_ID'] = $idno;
//$query = mysql_query ("INSERT INTO user_log VALUES('$idno',NOW(), 'Login') ") or die(mysql_error());
header('location:plsvote.php');
}
}
else{
header('location:notification.php');
exit();
}
}

Categories