Log in and run query based on a select value - php

Im trying to use a select box to run different sql to log the user into my site. But for some reason it doesnt work. It "just shows the This user does not exist, please register first if you wish to continue message" that i have at the end.
My plan was just to get the value by using $_POST and storing it in a variable and then just say if that equals this then run this sql to change the value of $databpass and $databuser. (See code for more)
Also for some reason the first if statement works and i can log in. I tried else if but that was the same.
All Help Appreciated thx :D
Please bare in mind that i am fairly new to stackoverflow and php
$username = $_POST ['Username'];
$password = $_POST ['Password'];
$c= $_POST ['ch'];
if ($c=="S")
{
include 'connect.php';
$squery = mysql_query("SELECT * FROM S WHERE Username='$username'" );
$snumrow = mysql_num_rows($squery) or die(mysql_error());
if ($snumrow!=0)
{
while($row = mysql_fetch_assoc($squery)){
$databuser = $row['Username'];
$databpass = $row['Password'];
}
}
}
if ($c=="Or")
{
include 'connect.php';
$oquery = mysql_query("SELECT * FROM O WHERE Username='$username'" );
$onumrow = mysql_num_rows($oquery) or die(mysql_error());
if ($onumrow!=0)
{
while($row = mysql_fetch_assoc($oquery)){
$databuser = $row['Username'];
$databpass = $row['Password'];
}
}
}
if ($c== "C")
{
$query = mysql_query("SELECT * FROM C WHERE Username='$username'" );
$numrow = mysql_num_rows($query) or die(mysql_error());
if ($numrow!=0)
{
while($row = mysql_fetch_assoc($query)){
$databuser = $row['Username'];
$databpass = $row['Password'];
}
}
}
if ($username==$databuser&&$password==$databpass)
{
$_SESSION['username']=$username;
setCookie("sessionUsername", $username, time()+ 3600);
header("Location: memberprofile.php");
}
else
echo "Incorrect pass";
}
else
die("This user does not exist, please register first if you wish to continue");

Related

how to retrive data from database using mysqli_fetch_array in php

How can retrive data.here login not working.I used mysqli_fetch_array,but before while the condition failed.
<?php
session_start();
include 'db.php';
$username = $_POST['username'];
$password = $_POST['password'];
$query = mysqli_query($connect,"SELECT * FROM tbl-login where username='".$username."'");
$n = 0;
while($row = mysqli_fetch_array($query)) {
// $u-id = $row['u-id'];
$dbusername = $row['username'];
$dbpassword = $row['password'];
$usertype = $row['usertype'];
$_SESSION['usname'] = $dbusername;
$_SESSION['uid'] = $u-id;
$_SESSION['usertype'] = $usertype;
if ($dbusername == $username && $dbpassword == $password) {
$n++;
echo "grtet";
// header('location:dashboard.php');
}
}
if ($n == 0) {
header('location:index.php');
}
?>
$query = mysqli_query($connect,"SELECT * FROM tbl-login where username='".$username."' and password='".$password."'");
$row = mysqli_fetch_row($query); // Just ONE row, because expecting is, there is only one user with this USERNAME
if(empty($row)) {
echo 'Invalid username or password';
}else{
echo 'OK :)';
}
When you're not sure what makes a query fail, call mysqli_error(). While I haven't tested myself, I believe tbl-login is the cause of the error (which mysqli_error() should return if you call it).
MySQL allows spaces and non-identifier characters to be table/column name, but when referring to such a name, you need to enclose it between backtick (`). Hence tbl-login should be written as `tbl-login` in the SQL query.
You Have Created table name as tbl-login, column name as u-id and variable as $u-id, which i think is a problem. If Possible, change your column name, table name and variable name. Here are some links to get basic idea for creating variable name, column name, table name.
Create Variables, Create Table, Identifiers
I've updated your code. Please have a look.
<?php
session_start();
include 'db.php';
$username = $_POST['username'];
$password = $_POST['password'];
$query = mysqli_query($connect,"SELECT * FROM `tbl_login` WHERE username='$username' AND password='$password'");
$rowcount = mysqli_num_rows($query);
if($rowcount > 0) {
while($row = mysqli_fetch_array($query,MYSQLI_ASSOC)) {
$_SESSION['usname'] = $row['username'];
$_SESSION['uid'] = $row['u_id'];
$_SESSION['usertype'] = $row['usertype'];
header('location:dashboard.php');
}
} else {
header('location:index.php');
}
?>

PHP: else condition is not working in php

I have designed a admin login page. The if condition is working but else condition is not. After putting wrong username or password it shows blank on the same page.
if(isset($_POST['submit']))
{
$userid = $_POST['userid'];
$pass= $_POST['pass'];
$sql = mysqli_query($DBCONNECT, "SELECT * FROM admin WHERE userid='$userid' and pass='$pass'") or die(mysql_error());
//$count=mysql_fetch_array($sql);
$count = mysqli_num_rows($sql) or die(mysql_error());
if($count == 1)
{
$_SESSION['userid'] = $userid;//$_POST['userid'];
echo "hiii";
//header("Location:add_menu.php");
}
else
{
echo "Wrong Username or Password";
}
}
You used mysql_error(); which is causing the error of blank page.
Use the below code will fix your problem.
$sql = mysqli_query($DBCONNECT,$query);
$count = mysqli_num_rows($sql);
Remove or die(mysqli_error($link)) from your code that will work fine for you.
Note: mysqli_num_rows can be used for Procedural style only not for object oriented style.
Can you try with this code? Difference is putting if($count) instead of if($count==1)
if(isset($_POST['submit']))
{
$userid = $_POST['userid'];
$pass= $_POST['pass'];
$sql = mysqli_query($DBCONNECT, "SELECT * FROM admin WHERE userid='$userid' and pass='$pass'") or die(mysql_error());
//$count=mysql_fetch_array($sql);
$count = mysqli_num_rows($sql) or die(mysql_error());
if($count)
{
$_SESSION['userid'] = $userid;//$_POST['userid'];
echo "hiii";
//header("Location:add_menu.php");
}
else
{
echo "Wrong Username or Password";
}
}
Mysqli Also make result as object so you can do this :
$sql = mysqli_query($con, "SELECT * FROM users WHERE userid='$userid' and pass='$pass'") or die(mysqli_error());
your mysqli_error only will show if statement wrong and i don't think you will put wrong statement but good in development.
then you can check if statement works by if and put this :
echo $sql->num_rows;
can put in variable :
$count = mysqli_num_rows($sql) to $count = $sql->num_rows
or
if($sql->num_rows == 0) {
// here your blank result for error
} else {
// show result here.
}
Link : Check PHP Site Mysqli Num Rows Result

This webpage has a redirect loop PHP issue?

I am using the following codes in my login.php and index.php files.
I get the This webpage has a redirect loop error in the browser.
I know the issue is caused by the logic in the login.php file by the following code:
$existCount = mysqli_num_rows($query); // count the row nums
if ($existCount == 1) { // evaluate the count
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
$_SESSION["id"] = $row["id"];
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
header("location: http://$storeShop.mysite.com/index.php");
exit();
} else {
echo 'That information is incorrect, try again Click Here';
exit();
}
specifically this line: header("location: http://$storeShop.mysite.com/index.php");
I just do not know how I can fix this issue!
LOGIN.PHP
<?php
session_start();
ob_start();
if (isset($_SESSION["manager"])) {
/*
IF THE USER IS LOGGED IN THE CODE BELOW SENDS THEM TO THEIR OWN SUBDOMAIN NAME
WHICH IS STORED IN $_SESSION["storeShop"].
CHANGE "REST_OF_URL" TO THE VALID DOMAIN IN THE HEADER FUNCTION.
BUT DON'T REMOVE THE . (DOT)
*/
header("Location: http://$_SESSION[storeShop].mysite.com/index.php");
exit();
// END OF EDIT.
}
?>
<?php
if (isset($_POST["email"]) && isset($_POST["password"])) {
$manager = $_POST["email"]; // filter everything but numbers and letters
$password = (!empty($_POST['password'])) ? sha1($_POST['password']) : ''; // filter everything but numbers and letters
$storenameTable = $_REQUEST['storeShop'];
// Connect to the MySQL database
include "config/connect.php";
$sql = "SELECT members.id, members.email, members.password, members.randKey, members.storeShop, storename.email, storename.password, storename.randKey, storename.storeShop
FROM members
INNER JOIN storename ON members.randKey = storename.randKey
WHERE members.email = '$manager'
AND members.password = '$password'
";
$result = mysqli_query($db_conx,"SELECT storeShop FROM members WHERE email='$manager' AND password='$password'");
while($row = mysqli_fetch_array($result))
{
$email = $row["email"];
$password = $row["password"];
$storeShop = $row["storeShop"];
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
$_SESSION['storeShop'] = $storeShop;
}
// query the person
// ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
$query = mysqli_query($db_conx, $sql);
if (!$query) {
die(mysqli_error($db_conx));
}
$existCount = mysqli_num_rows($query); // count the row nums
if ($existCount == 1) { // evaluate the count
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
$_SESSION["id"] = $row["id"];
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
header("location: http://$storeShop.mysite.com/index.php");
exit();
} else {
echo 'That information is incorrect, try again Click Here';
exit();
}
}
?>
INDEX.PHP
<?php
session_start();
ob_start();
if (!isset($_SESSION["manager"])) {
header("location: login");
exit();
}
/*
THE CODE BELOW COMPARES THE SUBDOMAIN TO THE USER'S STORESHOP SESSION
IF THEY DON'T MATCH IT REDIRECTS THEM TO THEIR SUBDOMAIN.
CHANGE "REST_OF_URL" TO THE VALID DOMAIN IN THE HEADER FUNCTION.
BUT DON'T REMOVE THE . (DOT)
*/
else {
$url = $_SERVER["HTTP_HOST"];
$user_subdomain = explode(".", $url);
if($_SESSION["storeShop"] != $user_subdomain[0]) {
header("Location: http://$_SESSION[storeShop].mysite.com/index.php");
}
}
ob_end_flush();
// Be sure to check that this manager SESSION value is in fact in the database
$managerID = preg_replace('#[^0-9]#i', '', $_SESSION["id"]); // filter everything but numbers and letters
$manager = $_POST["email"]; // filter everything but numbers and letters
$password = (!empty($_POST['password'])) ? sha1($_POST['password']) : ''; // filter everything but numbers and letters
$storenameTable = $_REQUEST['storeShop'];
// Run mySQL query to be sure that this person is an admin and that their password session var equals the database information
// Connect to the MySQL database
include "config/connect.php";
$sql = "SELECT members.id, members.email, members.password, members.randKey, members.storeShop, storename.email, storename.password, storename.randKey, storename.storeShop
FROM members
INNER JOIN storename ON members.randKey = storename.randKey
WHERE members.email = '$manager'
AND members.password = '$password'
"; // query the person
// ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
$query = mysqli_query($db_conx, $sql);
if (!$query) {
die(mysqli_error($db_conx));
}
$result = mysqli_query($db_conx,"SELECT storeShop FROM members WHERE email='$manager' AND password='$password'");
while($row = mysqli_fetch_array($result))
{
$email = $row["email"];
$password = $row["password"];
$storeShop = $row["storeShop"];
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
$_SESSION['storeShop'] = $storeShop;
}
?>
could someone please point me in the right direction?
Thanks in advance.
You have started another session in index.php using session_start()
Remove the session_start() from index.php page and confirm if it is working fine
You're redirecting users to a different subdomain, and probably losing all your session data in the process.
Before you call session_start(), make sure your cookies are valid for the whole domain, i.e.,:
session_set_cookie_params(0, '/', '.mysite.com');
session_start();
More information here
Edit: Some other things you should look into:
(1) After the user has been redirected to "login" (header("location: login");), which of your scripts will process the next request? (Did you mean login.php?)
(2) What does login.php do when it receives a GET request (without an active session)?

mySQL statement not working inside of php

Im trying to do a login system for my website and I changed around how it is implemented and it broke, whenever I try to login with a correct login it fails to take me to the next page, here is my php:
<?php
//finds the correct database
$sql_link = mysqli_connect("localhost", "root" , "12buckle", "GameData");
if (mysqli_connect_errno())
{
echo "Failed to connect to databse: " . mysqli_connect_error();
}
if (isset($_POST['Username']))
{
$username = mysql_real_escape_string($_POST['Username']);
$password = mysql_real_escape_string($_POST['Password']);
//checking to see if password and username can be found in student database
//loading in correct data
$login = mysqli_query($sql_link,"SELECT * FROM tblStudents WHERE UserName='$username' AND Password='$password'");
if ($login['Password'])
{
$_SESSION['name'] = $login['StudentFirstName'];
$_SESSION['ClassID'] = $login['ClassID'];
$_SESSION['ID'] = $login['StudentID'];
header ("Location: index.php");
}
else
{
$login = mysqli_query($sql_link,"SELECT * FROM tblTeacher WHERE Username='$username' AND Password='$password'");
if ($login['Password'])
{
$_SESSION['name'] = $login['TeacherSurname'];
$_SESSION['title'] = $login['Title'];
$_SESSION['ID'] = $login['TeacherID'];
header ("Location: TeacherSide.php");
}
else
{
echo 'Login details incorrect';
}
}
}
Also if it helps when I ran it last night im sure it worked, but I was half awake so I may have been testing the old version
Your logic is faulty. mysql_query returns a result HANDLE. it does not return any actual data. You need to fetch a row first, before checking for actual data:
$result = mysqli_query($sql_link, "SELECT * FROM tblStduents ....");
if (mysqli_num_rows($result) > 0) {
... got a student record
$row = mysqli_fetch_assoc($result);
echo $row['StudentFirstName'];
} else {
... no student rows, repeat with teachers
}
I've had issues in the past where variables aren't read properly the way you have them in your SQL statements.
Try Username='" . $username . "' AND instead and see what happens.

PHP Session not holding values

After a good few hours of looking at posts and different forums I finally give up.
I have been learning PHP for the last 24 hours by trying to create a registration and a login page.
Registration seems to be working (I am sure that there are some bugs etc, but as of right now everything seems to be in sql).
As far as my login page, this is where I am having some problems.
NEW EDIT
Here is my registration.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//Set error msg to blank
$errorMsg = "";
// Check to see if the form has been submitted
if (isset($_POST['username']))
{
include_once 'db_connect.php';
$username = preg_replace('/[^A-Za-z0-9]/', '', $_POST['username']);
$password = preg_replace('/[^A-Za-z0-9]/', '', $_POST['password']);
$accounttype = preg_replace('/[^A-Za-z]/','', $_POST['accounttype']);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
//validate email with filter_var
if ((!$username) || (!$password) || (!$accounttype) || (!$email))
{
$errorMsg = "Everything needs to be filled out";
}
else {
// if fields are not empty
// check if user name is in use
$db_username_check = mysql_query("SELECT id FROM members WHERE username='$username' LIMIT 1");
$username_check = mysql_num_rows($db_username_check);
// check if email is in use
$db_email_check = mysql_query("SELECT id FROM members WHERE email='$email' LIMIT 1");
$email_check = mysql_num_rows($db_email_check);
//if username is in use ... ERROR
if ($username_check > 0) {
$errorMsg = "ERROR: username is already in use";
// if username is ok check if email is in use
} else if ($email_check > 0) {
$errorMsg = "ERROR: email is already in use";
} else {
session_start();
$hashedPass = md5($password);
// Add user info into the database table, claim your fields then values
$sql = mysql_query("INSERT INTO members (username, password, email, accounttype )
VALUES('$username', '$hashedPass', '$email', '$accounttype')") or die (mysql_error());
// Retrieves the ID generated for an AUTO_INCREMENT column by the previous query
$id = mysql_insert_id();
$_SESSION['id'] = $id;
mkdir("members/$id", 0755);
header("location: member_profile.php?id=$id");
$errorMsg = "Registration Successful";
exit();}
}
// if the form has not been submitted
} else { $errorMsg = 'To register please fill out the form'; }
?>
here's my Login.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// if the form has been submitted
$errorMsg = "";
if ($_POST['username']){
include_once('db_connect.php');
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$hashedPass = md5($password);
$sql = "SELECT username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
$login_check = mysql_query($sql);
$count = mysql_num_rows($login_check);
$row = mysql_fetch_array($login_check);
//var_dump($id, $username, $password);
if($count==1)
{
session_start();
//$id = $row["id"];
// $_SESSION['id'] = $userid;
// $username = $row['username'];
// $_SESSION['username'] = $username;
// header("location: member_profile.php?id=$userid");
echo "User name OK";
return true;
} else {
echo "Wrong username or password";
return false;
}
}
?>
Whenever someone registers $id = mysql_insert_id();will pull the ID from the last query and start a $_SESSION['id']. However during a login right after if($count==1) I am completely lost. For some reason the name and the password is checked and does go through but the ID fails.
I did try adding "SELECT id FROM members WHERE id='$id'" but my $id is always undefined.
My member_profile.php is something like this:
<?php
session_start();
$toplinks = "";
if(isset($_SESSION['id'])) {
//If the user IS logged in show this menu
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '
Profile •
Account •
Logout
';
} else {
// If the user IS NOT logged in show this menu
$toplinks = '
JOIN •
LOGIN
';
}
?>
Thank you to everyone for any tips as far as security, structure and coding style. This is day #3 of php for me.
Please excuse any errors.
Your if is going inside comments check this --
<?php // if the form has been submitted $errorMsg = ""; if
edit it --
<?php
// if the form has been submitted
$errorMsg = "";
if(($_POST['username']) && ($_POST['password'])){
You are using mysql and using mysqli in your code too--
$row = mysqli_fetch_array($sql);
use --
$row = mysql_fetch_array($sql);
Look at your sessions as well as Phil mentioned in comments.
session_start()
Replace the code
$row = mysqli_fetch_array($sql); to $row = mysql_fetch_array($login_check);
if($count==1)
{
$id = $row['id'];
session_start();
$_SESSION['id'] = $id;
//$row = mysqli_fetch_array($sql);
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
exit();
} else {
echo "Wrong username or password";
return false;
}
Also Change your query if you have any id field in table:
$sql = "SELECT id,username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
First I went over the code. Since this is my day #4 of php, I started changing everything from mysql to mysqli which made a little more sense to me. The code is probably still messy but it does work so far. Thank you
$sql = ("SELECT * FROM members WHERE username = '$username' && password = '$hashedPass'");
$login_check = mysqli_query($link, $sql);
$count = $login_check->num_rows;
$row = mysqli_fetch_array($login_check);
printf("Result set has %d rows.\n", $count);
if($count==1)
{
session_start();
$id = $row["id"];
$_SESSION['id'] = $id;
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
echo "User name OK";
return true;

Categories