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');
}
?>
Related
I am having problem with the code.
It suppose to allow admin to view only admin page
and user to view user page only.
my admin still able to view user page.
below is my landing page
<?php
error_reporting(0);
include("config.php");
$host = "localhost"; //DB host
$username = "root"; //DB Username
$password = ""; //DB Password
$db_name = "hklcanet_pha"; //DB Name
$tbl_name = "users"; //Table name, where users are stored
$dbconfig = mysqli_connect($host,$username,$password,$db_name);
$username = $_POST['username']; //Get username from login form
$password = $_POST['password']; //Get password from login form
$username = stripslashes($username); //Makes string safe
$password = stripslashes($password); //Makes string safe
$username = mysqli_real_escape_string($dbconfig, $username); //Makes string safer
$password = mysqli_real_escape_string($dbconfig, $password); //Makes string safer
$sql = "SELECT * FROM $tbl_name WHERE username='$username' and password='$password'"; //SQL Query
$result = mysqli_query($dbconfig, $sql); //Executes Query
$rows = mysqli_num_rows($result); //Count rows selected (1 if a username/password combo can be found)
if($rows == 1){
session_start(); //Starts a PHP session
$_SESSION['username'] = $username; //Allows $username to be used later
header("location: interphase1.php");
$query = "SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
$result = mysqli_query($dbconfig, $query);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$permissions = $row['permissions']; //Gets the permissions of the user
$id = $row['id']; //Gets the ID of the user
}
$_SESSION['permissions'] = $permissions; //Allows $permissions to be used later
$_SESSION['id'] = $id; //Allows $id to be used later
$_SESSION['authenticated'] = 1; //Allows $id to be used later
echo("Login Succesful");//Prints success message
}
else
{
//echo("Invalid Username/Password");
}
?>
user page
<?php
session_start();
$permissions = $_SESSION['permissions'];
if($_SESSION['authenticated'] != 1)
{
echo("You must be logged in");
header("location:landing.php");
}
else
{
if($permissions < 0)
{
header("location:quicksummary.php");
echo("Your permissions are not high enough");
}
}
?>
admin page
<?php
session_start();
$permissions = $_SESSION['permissions'];
if($_SESSION['authenticated'] != 1)
{
header("location:landing.php");
echo("You must be logged in");
}
else
{
if($permissions < 1 )
{
header("location:quicksummary.php");
echo("Your permissions are not high enough");
}
}
?>
thanks and appreciate if somebody can help me on this, still new with the PHP code.
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");
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)?
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;
How would I make this work, I asked before and didn't get a correct answer. This code is the user login, so when they log in I want username and avatar to be trackable through out the site. So far I just have username. I have tried methods and have failed every time.
$username = $_POST['username'];
$password = sha1($_POST['password']);
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $sql) or die('Error querying database.');
$count=mysqli_num_rows($result);
if ($count == 1)
{
$row = mysqli_fetch_array($result);
while ($_SESSION['username'] = $row['username'])
{
session_start();
header('Location: index.php');
}
}
else
{
echo 'Invalid Logins';
}
mysqli_close($conn);
?>
Supposing you have avatar stored in the avatar field in the database:
if ($count == 1)
{
session_start();
$row = mysqli_fetch_array($result);
$_SESSION['username'] = $row['username'];
$_SESSION['avatar'] = $row['avatar'];
header('Location: index.php');
}
else
{
echo 'Invalid Logins';
}