I hope that I describe my problem properly. I have created a database for a cafeteria. This has the following tables: orders, members ISA manager and servers, products and categories. In the table orders I should insert features such as title,quantity,datetime,sum and user name of the corresponding server. I've managed to do so via php in my files posted before in this forum (follow the link: Insert data from textbox and checkbox into database ).
The web environment so far is consisted of :
a)index.php, members.php (these files are responsible for the login and the authentication of any kind of user, either the administrator or serves.
b)addorder_form.php and addorder.php as far the order form and the insert of the order details in database.
I cannot make my system print the username of each server for each order.
I tried something like this but I 've got the error of undefined index username :
<?php
session_start();
include_once("buzzcafe_fns.php");
include_once("members.php");
do_html_header("");
$conn = mysql_connect("localhost", "root", "");
$db=mysql_select_db("buzzcafe" ,$conn);
db_connect();
if (isset($_SESSION['username']){
if (isset($_POST['products'])) {
if (isset($_POST['quantity'])) {
foreach($_POST['products'] as $key => $products){
$quantity = isset($_POST['quantity'][$key])? $_POST['quantity'][$key]:'Not selected';
date_default_timezone_set('Europe/Athens');
$date = date('Y-m-d H:i:s');
$message[] = $products.' - x'.$quantity;
$insertOrder = mysql_query("INSERT INTO orders (datetime,title,quantity,username) VALUES('".$date."','".$products."','".$quantity."', '".$_SESSION['username']."')")or die(mysql_error());
echo $_SESSION['username'];
}
}
echo implode(',', $message);
echo "<br/>";
echo "<br />Record inserted";
echo "<br/>";
echo $date;
}
else { echo "You did not choose a quantity."; }
}else { echo "You did not choose any product."; }
}
?>
Why is username undefined?
A part of members.php:
<?php
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if ((!$username) || (!$password)) {
do_html_header('');
echo '<h3 style="color:#800000;">Please fill in both fields</h3><br><br></br></br>';
display_login_form();
}
else {
$sql = mysql_query('SELECT * FROM members WHERE username="'.$_POST['username'].'" AND password=sha1("'.$_POST['password'].'")') or die(mysql_error());
$login_check_member = mysql_num_rows($sql);
if($login_check_member > 0) {
while($row = mysql_fetch_array($sql)) {
$role = $row["role"];
$_SESSION['role'] = $role;
$us = $row["username"];
$_SESSION['username'] = $us;
$username = $_SESSION['username'];
}
}
I include this file in my addorder.php file.
Probably because it's not defined?
Seems people are a little more concerned about your SQL than anything -- but this may help you in the actual question.
Throw this in there before them nested conditions:
if (defined($_SESSION['username'])) {
echo 'Username is defined!';
}
else {
die('Username is undefined!');
}
Related
This works perfectly well on my localhost but when i hosted online, it does not logon and it echo logged on successful and error free. Pls what can be the cause for this?
<?php
session_start();
$_SESSION['user_logged']=$user;
$_SESSION['user_password']=$password;
$user = $_POST["username"];
$password = $_POST["password"];
include("include/connect.php");
$msg = array();
if(isset($_POST['submit'])){
foreach($_REQUEST as $key=>$val){
$$key=$val;
}
if(count($msg)==0){
$sql="SELECT username, password FROM admin WHERE username='$username' && password='$password'";
$res=mysql_query($sql) OR die(mysql_error());
if(mysql_fetch_array($res)>0){
$_SESSION['user_logged']= $user;
$_SESSION['user_password']=$password;
header("location:dashboard.php");
echo "You looged in Successfully";
} else{
$msg[]='Incorrect username/password';
}
}
}
?>
Below is the dashboard.php which its suppose to redirect to.
<?php
include('include/connect.php');
include('include/function.php');
if(isset($_REQUEST['mode']) )
{
$mode=$_REQUEST['mode'];
if($mode == 1)
{
$id=$_REQUEST['id'];
$sql="DELETE FROM enquiry WHERE id='$id'";
$result=mysql_query($sql);
}
}
$msg=array();
if(isset($_POST['submit'])){
$title=$_POST['news'];
$news_item=$_POST['news'];
if(empty($news_item)){
$msg[]='You must enter news in the column!';
}
if(empty($title)){
$msg[]='News Title must not be empty!';
}
else {
$sql = "SELECT * FROM news_file WHERE title='$title' ";
$res = mysql_query($sql) or die(mysql_error());
$result = mysql_fetch_array($res);
if($result > 0){
$msg[] = 'News with the same title has been added already';
} else {
$sql = "INSERT INTO news_file (title,news,date) VALUES ('$title','$news_item',Now())";
$result = mysql_query($sql);
$msg[]='News was successfully added';
}
}
}
?>
Try this.
<?php
session_start();
/*
These should be the other way round, as you are setting
the session variables with variables which have not been
initialised yet
*/
$user = $_POST["username"];
$password = $_POST["password"];
$_SESSION['user_logged']=$user;
$_SESSION['user_password']=$password;
include("include/connect.php");
$msg = array();
if(isset($_POST['submit'])){
foreach($_REQUEST as $key=>$val){
$key=$val; // Removed Erroneous double $
}
if(count($msg)==0){
$sql="SELECT
username,
password
FROM
admin
WHERE
username='$username'
AND
password='$password'";
// MySql does not accept && as a comparison operator.
$res=mysql_query($sql);
if(!$res)
{
var_dump(mysql_error());
exit;
}
else
{
if(mysql_fetch_array($res)>0)
{
$_SESSION['post'] = $_POST;
while(mysql_fetch_array($res)>0)
{
$_SESSION['user_logged']= $user;
$_SESSION['user_password']=$password;
header("location:dashboard.php");
echo "You logged in Successfully";
}
}
else
{
msg[]='Incorrect username/password';
}
}
?>
Looking at the code you have provided for dashboard.php, you are expecting there to be $_POST data, for a page which you have redirected to. Where you have redirected to the page, there will be no $_POST data for you to retrieve from the server.
I have amended my script above, to store the $_POST data in the session, so using that, you should be able to call your news items by calling $_SESSION['post']['news'], or if this is too long winded, simply re-assign the POST data once inside your dashboard.php script like so.
$post = $_SESSION['post'];
Then you can call it by using $post['news'].
I am trying to make a login form which is able to detect whether the user is admin or non-admin. I tried the following but when i run it i get no results:
<?php
session_start();
$message = "";
if(count($_POST)>0)
{
$conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "prosoftl_rcc", "Royal"));
((bool)mysqli_query($conn, "USE prosoftl_rcc"));
$result = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM student WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$row = mysqli_fetch_array($result);
$a = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM teacher WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$r = mysqli_fetch_array($a);
if(is_array($row))
{
$_SESSION["id"] = $row[id];
$_SESSION["name"] = $row[name];
}
elseif(is_array($r))
{
$_SESSION["admin"] = $row[id];
}
else
{
$message = "Invalid Username or Password!";
}
}
if(isset($_SESSION["id"]))
{
header("Location:user_dashboard.php");
}
elseif(isset($_SESSION["admin"]))
{
header ("location:gui-admin.php");
}
?>
When i insert the username and password for admin it reloads the login form.
UPDATE 1:
The non-admin part is just working fine but the admin part redirects/reloads itself to the login form.
you should check your login post form,should have a code like this:
<form name="loginform" method="post" action="check.php">
if your 'action' vlaue is invalid,the page may refresh.
you should confirm that your login form is posted to the php page you posted.
Try this, lets see what happens.
session_start();
$msg = "";
if(count($_POST)>0){
$conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "prosoftl_rcc", "Royal"));
((bool)mysqli_query($conn, "USE prosoftl_rcc"));
$result = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM student WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$stdCount = mysqli_num_rows($result);//counts the number or rows returned from student table
$a = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM teacher WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$tchrCount = mysqli_num_rows($a);// same but with teachers table
if($stdCount != 0){
$row = mysql_fetch_array($result);
$_SESSION['id'] = $row['id']; //set session for non admin.
}else if($tchrCount != 0){
$r = mysql_fetch_array($a);
$_SESSION['admin'] = $r['id'];
}else{
echo "Username and Password is not Matching.";
}
}//end of the main if
I have not tested this code so dunno if it works or not but I think you got the logic.
use quotes: $row["id"]
"Location: " must be capital.
after calling the "header" function make sure you use "exit".
This code is not tested, but if I understood correctly, should work.
<?php
session_start();
$message = "";
if(count($_POST)>0)
{
$conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect("localhost", "prosoftl_rcc", "Royal"));
((bool)mysqli_query($conn, "USE prosoftl_rcc"));
$result_student = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM student WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$row_student = mysqli_fetch_array($result_student);
$result_teacher = mysqli_query($GLOBALS["___mysqli_ston"], "SELECT * FROM teacher WHERE name='" . $_POST["user_name"] . "' and password = '". $_POST["password"]."'");
$row_teacher = mysqli_fetch_array($result_teacher);
if(is_array($result_student))
{
$_SESSION["id"] = $row_student["id"];
$_SESSION["name"] = $row_student["name"];
$_SESSION["admin"] = 0;
}
elseif(is_array($result_teacher))
{
$_SESSION["id"] = $row_teacher["id"];
$_SESSION["name"] = $row_teacher["name"];
$_SESSION["admin"] = $row_teacher["id"];
}
else
{
$message = "Invalid Username or Password!";
}
}
if(isset($_SESSION["id"]))
{
if(#$_SESSION["admin"]>0)
{ header ("Location: gui-admin.php");
exit;
}
else
{ header("Location: user_dashboard.php");
exit;
}
}
?>
Hope it helps....
But I can guess why you are facing the problem for your code only working for students.
In this -
if(is_array($row))
is_array($row) would always be returning true and the code goes on to execute
$_SESSION["id"] = $row[id];
$_SESSION["name"] = $row[name];
but $row[id] would be empty because there are no rows matching the criteria, so $_SESSION["id"] would not be assigned and when this is executed -
if(isset($_SESSION["id"]))
{
header("Location:user_dashboard.php");
}
elseif(isset($_SESSION["admin"]))
{
header ("location:gui-admin.php");
}
None of the if statements would not be executed because none of them are set. This is my analysis. This could be wrong.
Try the solution below -
You should combine the users table for just querying whether the user is a student or a teacher. You then query the student table or the teacher table depending on the Main "Users" table. Querying for the same username and password to two tables doesnt look good.
You can change the meta tag in my code to header("Location: $url") but I would prefer this so that the request doesnt get cached by the user.
Hope it helps :-
$sql="SELECT * FROM {$table} WHERE username='{$username}' and password='{$password}'"; //My variables are already filtered and safe from SQL Injection.
$result=mysqli_query($mysqli, $sql);
if(mysqli_num_rows($result))
{
$fetch=mysqli_fetch_row($result);
$_SESSION["id"]=$fetch['userid'];//Just fetching all details
$_SESSION["Name"]=$fetch['name'];//and making session variables for that.
$_SESSION["username"]=$fetch['username'];
$isadmin=$fetch['isadmin']; //is a BOOL value in MySQL table.
if($isadmin) //checking whether admin or not
{
$_SESSION["isadmin"]=1;
echo "<meta http-equiv='refresh' content='0;url=adminurl'>"; } //if admin redirect to different url
else{
$_SESSION["isadmin"]=0;
echo "<meta http-equiv='refresh' content='0;url=userurl'>";
}
}
else
{
//Username Password Incorrect
/* Show FORM HERE */
}
First of all, you have to know that's really a bad idea to use your POST data directly in your SQL request, you have to avoid that and to clean your data using a function like mysqli_real_escape_string. Also, you have to secure your passwords and avoid to save it clear into your DB, for that take a look on the best way to store password in database.
For your two SQL requests, you can use mysqli_multi_query like I did in this example where I used the same script to get POST data and show the login form :
<?php
if(count($_POST) > 0){
session_start();
$link = mysqli_connect('localhost', 'user', 'pass', 'db');
if(mysqli_connect_errno()) {
die('db connection error : ' . mysqli_connect_error());
}
function secure_password($password){
// secure your password here
return $password;
}
// escape special characters
$user_name = mysqli_real_escape_string($link, $_POST['user_name']);
// you have to secure your passwords, when saving it of course
$password = secure_password(mysqli_real_escape_string($link, $_POST['password']));
$query = "SELECT id FROM student WHERE name = '".$user_name."' and password = '".$password."';";
$query .= "SELECT id FROM teacher WHERE name = '".$user_name."' and password = '".$password."'";
$is_teacher = FALSE;
if(count($_SESSION)) session_destroy();
// you can use mysqli_multi_query for your two requests
if (mysqli_multi_query($link, $query)) {
do {
if ($result = mysqli_store_result($link)) {
if ($row = mysqli_fetch_row($result)) {
if($is_teacher){
$_SESSION['admin'] = $row[0];
} else {
$_SESSION['id'] = $row[0];
$_SESSION['name'] = $user_name;
}
}
mysqli_free_result($result);
}
if (mysqli_more_results($link)) {
// if we have more results, so it's a teacher record
$is_teacher = TRUE;
}
} while (mysqli_more_results($link) && mysqli_next_result($link));
}
mysqli_close($link);
if(isset($_SESSION['id']))
{
header('Location:user_dashboard.php');
}
elseif(isset($_SESSION['admin']))
{
header('Location:gui-admin.php');
}
// no redirection, show the message and the login form
echo 'Invalid Username or Password!';
}
?>
<form action='p.php' method='post'>
User name : <input type='text' name='user_name'><br>
Password : <input type='password' name='password'><br>
<input type='submit' value='Submit'>
</form>
Hope that can help.
I am trying to build a register page using PHP and MySQLi. However, it doesn't work, and I cannot understand the issue. It was previously with no MySQL improved syntax. There is just an empty page in browser.
<?php
include ("bd.php");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['login']))
{
$login = $_POST['login'];
if ($login == '')
{
unset($login);
}
}
if (isset($_POST['password']))
{
$password=$_POST['password'];
if ($password =='')
{
unset($password);
}
}
if (empty($login) or empty($password))
{
exit ("You have entered not all of the information, go back and fill in all the fields!");
}
$login = stripslashes($login);
$login = htmlspecialchars($login);
$password = stripslashes($password);
$password = htmlspecialchars($password);
$login = trim($login);
$password = trim($password);
$myrow = mysqli_query($db,"SELECT id FROM users WHERE login='$login'");
if (!empty($myrow['id']))
{
exit ("Sorry, you entered login which is already registered . Please enter a different username.");
}
$result2=mysqli_query($db,"INSERT INTO users (login,password) VALUES('$login','$password')");
if ($result2=='TRUE')
{
echo "You have successfully signed up!";
}
else
{
echo "Failed to sign up";
}
?>
bd.php:
<?php
$db = new mysqli ("localhost","root","root","kotik");
?>
<?php
include ("bd.php");
if (mysqli_connect_errno()){echo "Failed to connect to MySQL: " . mysqli_connect_error();}
$login = isset($_POST['login'] && !empty($_POST['login'])) ? stripslashes(trim($_POST['login'])) : null;
$password = isset($_POST['login'] && !empty($_POST['login'])) ? stripslashes(trim($_POST['login'])) : null;
$password = htmlspecialchars($password);
if (empty($login) || empty($password)){exit ("You have entered not all of the information, go back and fill in all the fields!");}
$res = mysqli_query($db,"SELECT id FROM users WHERE login='$login'");
$myrow = mysqli_fetch_assoc($res);
if (!empty($myrow['id'])) {
exit ("Sorry, you entered login which is already registered . Please enter a different username.");
}
$result2 =mysqli_query($db,"INSERT INTO users (login,password) VALUES('$login','$password')");
if ($result2 == true)//use true not 'True' because 'True' is a string
{
echo "You have successfully signed up!";
}
else {
echo "Failed to sign up";
}
?>
EDIT: You should use mysqli_fetch_assoc to get an associative array which corresponds to the fetched row or NULL if there are no more rows.
You cannot use the variable $myrow like this:
$myrow['id']
You need to get the row then you can treat it like an array. It would look something like this:
$row = $myrow->fetch_row()
$row['id']
this gets the first row of the results of the query. If the query returns multiple results you can use something like this:
while($row = $myrow->fetch_row()) {
$rows[]=$row;
}
Then you use $rows as a normal array and get the individual rows 1 by 1 in a for loop, then you can use the same format:
$temp = $rows[0];
$temp['id']
I have this problem with my web system. As administrator, my purpose is to register some users giving them username,password,firstname and lastname. I do that properly since all the records are inserted correctly. But when I'm trying to have access as one of those users, I cannot enter, geting the message "Username and password do not match". This is my login check code:
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $_POST['username'];
if ((!$username) || (!$password)) {
do_html_header('');
echo '<h3 style="color:#800000;">Please fill in both fields</h3><br><br></br></br>';
display_login_form();
}
else {
$sql = mysql_query('SELECT * FROM members WHERE username="'.$_POST['username'].'" AND password=sha1("'.$_POST['password'].'")') or die(mysql_error());
$login_check_member = mysql_num_rows($sql);
if($login_check_member > 0) {
while($row = mysql_fetch_array($sql)) {
$role = $row["role"];
$_SESSION['role'] = $role;
}
}
else { // Run this code if login_check is equal to 0 meaning they do not exist
do_html_header('');
echo '<h3 style="color:#800000;">The Username And Password do not match.</h3><br><br></br></br>';
display_login_form();
}
Apparently, there is a problem with my while loop. But it does work properly for those users inserted in my database via MySql console of wampserver. The problem exists only for the users inserted via the web site.
The part of code that I use to insert new users (servers) is :
$username = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$role = $_POST['role'];
$conn = mysql_connect("localhost", "root", "");
$db=mysql_select_db("buzzcafe" ,$conn);
//$username= $_SESSION['username'];
if (isset($_POST['username'])) {
if (isset($_POST['password'])) {
if (isset($_POST['firstname'])) {
if (isset($_POST['lastname'])) {
if(isset($_POST['role'])) {
$insertServer = mysql_query("INSERT INTO servers (username,password,firstname,lastname,role) VALUES('".$username."',sha1('".$password."'),'".$firstname."','".$lastname."','".$role."')")or die(mysql_error());
echo "<h5 style=color:#800000><i>The server ".$username." is now registered </i></h5>";
display_manager_menu();
}
}
}
}
}
Any ideas please?
Look at the table you INSERT the data ('servers'). It's different from the table you SELECT the data from ('members').
Don't use the mysql_query function, as it deprecated. Try using PDO or mysqli_query instead.
Don't ever use unfiltered input in your query.
Try using more secure functions for your login/registration form (like bcrypt, or password_hash). Look here.
I'm very new to using MySql and am having trouble retrieving values from my database. I was under the impression that i was going about it the correct way but my echo statements don't print anything.
I'd appreciate some help. My code is below. I know i'll have to add security later on like sanitizing user input.
<?php
$email = $_POST['email'];
$password = $_POST['password'];
$hashedPass = sha1($password);
if ((!isset($email)) || (!isset($password))) {
//Visitor needs to enter a name and password
echo "Data not provided";
} else {
echo "Received details $email and $password <br/>";
// connect to mysql
$mysql = mysqli_connect("localhost", "root", "root");
if(!$mysql) {
echo "Cannot connect to PHPMyAdmin.";
exit;
} else {
echo "Connected to phpmyadmin <br/>";
}
}
// select the appropriate database
$selected = mysqli_select_db($mysql, "languageapp");
if(!$selected) {
echo "Cannot select database.";
exit;
} else {
echo "DB Selected";
}
// query the database to see if there is a record which matches
$query = "select count(*) from user where email = '".$email."' and password = '".$hashedPass."'";
$result = mysqli_query($mysql, $query);
if(!$result) {
echo "Cannot run query.";
exit;
}
$row = mysqli_fetch_row($result);
$count = $row[0];
$userdata = mysqli_fetch_array($result, MYSQLI_BOTH);
echo $userdata[3];
echo $userdata['firstName'];
if ($count > 0) {
echo "<h1>Login successful!</h1>";
echo "<p>Welcome.</p>";
echo "<p>This page is only visible when the correct details are provided.</p>";
} else {
// visitor's name and password combination are not correct
echo "<h1>Login unsuccessful!</h1>";
echo "<p>You are not authorized to access this system.</p>";
}
?>
I believe the problem is that you call twice the *fetch* family function which will cause the $userdata to be empty.
From the documentation mysql_fetch_row will fetch the next row and move the internal data pointer ahead. So when you call mysqli_fetch_array($result, MYSQLI_BOTH) and I suppose the user/password is unique there is nothing to retrieve. Also another mistake you did is that your SELECT doesn't retrieve the actual user data, but just the count number for the user/password combination. So your userdata will be always incorrect, even if you fetch the data right.
So change your query to something like that:
$query = "select * from user where email = '".$email."' and password = '".$hashedPass."' LIMIT 1";
Then use mysql_fetch_array to check if the entry exist and then retrieve the user data.