employee daily sales submission form with respect to ID - php

After login, an employee has to update his daily product sales. For the purpose I have made 02 tables named registration and dailysales. Table registration verifies the userID and password for login of user and has link to enter daily sales in 'dailysales' table. How can I insert the userID of logged-in user from table 'registration' to table 'dailysales' automatically. Note: In Table 'dailysales' employee also has to put daily sales of products from html form. In below coding how can i add userID and user Name of logged-in user automatically alongwith entry of products.
coding for dailysales is as under:-
<?php
require('config.php');
//Start the Session
session_start();
if((isset($_POST['diaper']) && !empty($_POST['diaper']))
&& (isset($_POST['babylotion']) && !empty($_POST['babylotion']))
&& (isset($_POST['nfacewash']) && !empty($_POST['nfacewash']))
&& (isset($_POST['facewash']) && !empty($_POST['facewash']))
&& (isset($_POST['hremover']) && !empty($_POST['hremover']))){
$Diaper = $_POST ['diaper'];
$BabyLotion = $_POST ['babylotion'];
$Neem_fw = $_POST ['nfacewash'];
$Facewash = $_POST ['facewash'];
$Hair_remover = $_POST ['hremover'];
}
$sql= "INSERT INTO dailyrecord (babydiaper,babylotion,hairremover,neemfw,neetfw) VALUES ('$Diaper','$BabyLotion','$Neem_fw','$Facewash','$Hair_remover')";
if (mysqli_query ($connection, $sql)){
echo '<script>alert("Congratulations! You Have Successfully added your sale!");</script>';
}
else{
echo '<script>alert("Sorry! Please fill the fields marked with *!");</script>';
}
?>
Coding for login is as under:-
<?php
//Start the Session
session_start();
require('config.php');
// If the form is submitted or not.
// If the form is submitted
if (isset($_POST['id']) and isset($_POST['password'])){
// Assigning posted values to variables.
$E_id = $_POST['id'];
$P_word = $_POST['password'];
// Check if username is empty
if(empty(trim($_POST["id"]))){
$username_err = 'Please enter username.';
} else{
$U_name = trim($_POST["id"]);
}
// Check if password is empty
if(empty(trim($_POST['password']))){
$password_err = 'Please enter your password.';
} else{
$P_word = trim($_POST['password']);
}
// Checking the values are existing in the database or not
$query = "SELECT * FROM registeration WHERE employee_id='$E_id' and password='$P_word'";
$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
// If the posted values are equal to the database values, then session will be created for the user.
if ($count == 1){
$_SESSION['id'] = $E_id;
}else{
//If the login credentials doesn't match, he will be shown with an error message.
$fmsg = "Invalid Login Credentials.";
}
}
//if the user is logged in Greets the user with message
if (isset($_SESSION['id'])){
$E_id = $_SESSION['id'];
echo "<center><table border='2' style='background-color:#FFFFFF;border-collapse:collapse;border:2px solid #6699FF;color:#000000;width:60%'>
<tr>
<th>Distributor</th>
<th>Designation</th>
<th>City</th>
<th>Visiting Area</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr\t\t\t>";
echo "<td>" . $row['emp_name'] . "&nbsp". $row['f_name'] . "</td>";
echo "<td>" . $row['designation'] . "</td>";
echo "<td>" . $row['city'] . "</td>";
echo "<td>" . $row['varea'] . "</td>";
echo "</tr>";
}
echo "</center></table>";
echo "<br>";
echo "<a href='logout.php'>Logout</a>";
}
else{
echo '<center>Invalied Username or Password</center>';
}
?>

As the user only gets the opportunity to add a record after a successful login there is the session variable with his/her ID available to use for insertion into sales record. Assumed that the dailyrecord or dailysales table (?which?) has a column for the user ID called employee_id then you could try something like this.
<?php
require('config.php');
session_start();
$babydiaper = !empty( $_POST['diaper'] ) ? $_POST['diaper'] : false;
$babylotion = !empty( $_POST['babylotion'] ) ? $_POST['babylotion'] : false;
$neemfw = !empty( $_POST['nfacewash'] ) ? $_POST['nfacewash'] : false;
$neetfw = !empty( $_POST['facewash'] ) ? $_POST['facewash'] : false;
$hairremover = !empty( $_POST['hremover'] ) ? $_POST['hremover'] : false;
if( $babydiaper && $babylotion && $neemfw && $neetfw && $hairremover && isset( $_SESSION['id'] ) ){
$sql='insert into `dailyrecord` ( `employee_id`, `babydiaper`, `babylotion`, `hairremover`, `neemfw`, `neetfw` ) values (?,?,?,?,?,?)';
$stmt=$connection->prepare( $sql );
if( $stmt ){
$id=$_SESSION['id'];
$stmt->bind_param('isssss', $id, $babydiaper, $babylotion, $hairremover, $neemfw, $neetfw );
$message = $stmt->execute() ? 'Congratulations - the sale was added' : 'Bogus - the sale could not be added';
$stmt->close();
$connection->close();
} else {
$message='Sorry - there was a database problem. Please contact the administrator';
}
} else {
$message='One of more fields was empty...';
}
echo "<script>alert('$message');</script>";
?>

In your daily sales code, you can use the $_SESSION['id'] to get the id
$id=$_SESSION['id'];
So you can use it in your $sql. You need to create a column id in your dailyrecord table with foreign key to your registeration table (so both id's are equal)
$sql= "INSERT INTO dailyrecord (id,babydiaper,babylotion,hairremover,neemfw,neetfw) VALUES ($id,'$Diaper','$BabyLotion','$Neem_fw','$Facewash','$Hair_remover')";
Anyways, you should use prepared statements to avoid sql injection for your $sql

Related

PHP if statement within if statement

I'm building a php site where i want the user to create his company.
The script is checking if the user has any companies registered already and then it should display if he does or doesn't.
If he doesnt have a registered company, he should see a form where he can register.
If he choose to register a company the script will check for any company with the same name or insert the row.
My only problem is that when there's already a company with that name the echo doesnt display.
I have written inside the code where the problem is.
<?php
$con=mysqli_connect("mysql","USER","PASS","DB");
if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
$result_get_companies = mysqli_query($con,"SELECT * FROM companies WHERE userid='". $login_session ."' ORDER BY companyid ASC") or die(mysqli_error());
if (mysqli_num_rows($result_get_companies) >= 1) {
while($row_companies = mysqli_fetch_array( $result_get_companies )) {
$result_get_company_owner = mysqli_query($con,"SELECT username FROM users WHERE userid='". $login_session ."'") or die(mysqli_error());
$company_owner = mysqli_fetch_assoc($result_get_company_owner);
echo 'THIS WORKS';
}
} else {
if (isset($_POST['create_first_company']) && !empty($_POST['company_name'])) {
$company_name_unsafe = mysqli_real_escape_string($con, $_POST['company_name']);
$company_name = preg_replace("/[^a-zA-Z0-9\s]/","",$company_name_unsafe );
$check_companies = "SELECT companyid FROM companies WHERE company_name='". $company_name ."'";
$what_to_do_companies = mysqli_query($con,$check_companies);
if (mysqli_num_rows($what_to_do_companies) != 0) {
echo 'THIS DOESNT WORK
It does register that is should go here
because it does not insert new row.
and when the value is = 0 it does go
to else ELSE below and insert row.';
} else {
$result_create_company = mysqli_query($con,"INSERT INTO companies (companyname)
VALUES ('". $login_session ."')")
or die(mysqli_error());
echo 'THIS WORKS';
}
} else {
echo 'THIS WORKS!';
}
}
?>

PHP MySQL sign in form not working

I'm trying to sign users in. I've already made the sign up form, And the database is properly connected.
It keeps on skipping over the first IF statements and going to straight to the "something went wrong error".
Does anybody know why it's not working?
<?php
$pageTitle = "Sign In";
$pageCategory = "Sign In";
$pageCategoryurl = "/signin.php";
//signup.php
include($_SERVER["DOCUMENT_ROOT"] . "/inc/header.php");
include($_SERVER["DOCUMENT_ROOT"] . "/inc/search.php");
?>
<div class="content">
<div id="signinheader"><h2>Sign in</h2></div><div style="clear:both"></div>
<?php
if(isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true)
{
echo 'You are already signed in, you can sign out if you want.';
}
else
{
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
/*the form hasn't been posted yet, display it
note that the action="" will cause the form to post to the same page it is on */
echo '<form method="post" action="">
<table>
<tr>
<th><label for="username" class="signinlabel">Username:</label></th>
<td><input type="text" name="username" class="signininput"></td>
</tr>
<tr>
<th><label for="userpass" class="signinlabel">Password:</label></th>
<td><input type="password" name="userpass" class="signininput"></td>
</tr>
</table>
<input type="submit" value="Sign In" class="signinbutton">
</form>';
}
else
{
/* so, the form has been posted, we'll process the data in three steps:
1. Check the data
2. Let the user refill the wrong fields (if necessary)
3. Save the data
*/
$errors = array(); /* declare the array for later use */
if(!isset($_POST['username']) OR empty($_POST['username']))
{
$errors[] = 'The username field must not be empty.';
}
if(!isset($_POST['userpass']) OR empty($_POST['userpass']))
{
$errors[] = 'The password field must not be empty.';
}
if(!empty($errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/
{
echo '<div id="signinerror"><h3>Uh-oh.. a couple of fields are not filled in correctly..</h3>';
echo '<ul>';
foreach($errors as $key => $value) /* walk through the array so all the errors get displayed */
{
echo '<li class="signinerrorli">' . $value . '</li>'; /* this generates a nice error list */
}
echo '</ul></div><div style="clear:both"></div>';
}
else
{
//the form has been posted without, so save it
//notice the use of mysql_real_escape_string, keep everything safe!
//also notice the sha1 function which hashes the password
$username = $_POST['username'];
$userpass = sha1($_POST['userpass']);
$result = mysqli_query($con,"SELECT * FROM users
WHERE username = '$username' AND userpass = '$userpass");
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while signing in. Please try again later.';
//echo mysqli_error(); //debugging purposes, uncomment when needed
}
else
{
//the query was successfully executed, there are 2 possibilities
//1. the query returned data, the user can be signed in
//2. the query returned an empty result set, the credentials were wrong
if(mysqli_num_rows($result) == 0)
{
echo 'You have supplied a wrong user/password combination. Please try again.';
}
else
{
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
while($row = mysqli_fetch_assoc($result))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
$_SESSION['useremail'] = $row['useremail'];
}
echo 'Welcome, ' . $_SESSION['username'] . '. Proceed to the homepage.';
}
}
}
}
}
?>
</div>
<?php
include($_SERVER["DOCUMENT_ROOT"] . "/inc/footer.php");
?>
Your error is on your query:
$result = mysqli_query($con,"SELECT * FROM users
WHERE username = '$username' AND userpass = '$userpass");
You miss a quote at the end.
$result = mysqli_query($con,"SELECT * FROM users
WHERE username = '$username' AND userpass = '$userpass' ");
^here
Your query to the database is resulting in some sort of database failure, as !$result, as you have it, will only resolve to true when $result is false. In your case, $result would only be false if something went wrong with the query.
The answer? You have a syntax error:
You have this:
$result = mysqli_query($con,"SELECT * FROM users
WHERE username = '$username' AND userpass = '$userpass");
Where it should be this
$result = mysqli_query($con,"SELECT * FROM users
WHERE username = '$username' AND userpass = '$userpass'");
Do you see it? You were missing that last ' :)
I like to call these "missing semicolon" errors, because they're impossible to find, drive you crazy, and are so simple to fix that it makes you feel dumb.

validation php not working?

The following is the email verification code for my site.
The verification url sent to the user's email is as follows:
http://www.mywebsite.com/valid.php?confr=2774405&userid=2
Extra notes :
1) key is a column in my database which gets a random value on registration.
2) if $verify == 1 and password_in_db=== user_entered_password, then login takes place in the login page.
<?php
include 'connect.php';
$query = mysql_query("SELECT verify,key FROM users WHERE id = '$_GET['userid']'");
$details = mysql_fetch_assoc($query);
$verify = $details['verify'];
$confirm2 = $details['key'];
if($verify == "1") {
echo "Link Expired . Go to our login page :";
} else {
if (isset($_GET["confr"]) && isset($_GET["userid"])) {
$confirm1 =$_GET["confr"];
if($confirm1 == $confirm2) {
mysql_query("INSERT INTO users (`verify`) VALUES ('1') WHERE id = '$_GET["userid"]' ;");
echo "Thank You For Registering with us . Go to your LOGIN PAGE Here ";
} else {
echo "Invalid link ";
echo "Go to your LOGIN PAGE Here ";
}
} // of if isset
} // of else part
?>
Code for connect.php
<?php
mysql_connect("host", "username", "pass"); //connects to the server
mysql_select_db("database_name"); //selects the database
?>
The problem is that it is giving me a blank screen .
i believe the error lies in the sql
when ever i use a "WHERE" statement i always define as a variable, try this
<?php
include 'connect.php';
$user_id = $_GET["userid"];
$query = mysql_query("SELECT verify,key FROM users WHERE id = '$user_id'");
$details = mysql_fetch_assoc($query);
$verify = $details['verify'];
$confirm2 = $details['key'];
if($verify == "1"){
echo "Link Expired . Go to our login page :";
}
else{
if (isset($_GET["confr"]) && isset($_GET["userid"]))
{
$confirm1 =$_GET["confr"];
if($confirm1 == $confirm2){
mysql_query("INSERT INTO users (`verify`) VALUES ('1') WHERE id = '$user_id'");
echo "Thank You For Registering with us . Go to your LOGIN PAGE Here ";
}
else {
echo "Invalid link ";
echo "Go to your LOGIN PAGE Here ";
}
} // of if isset
} // of else part
?>
also, you have a semi colon in the insert sql
Try this.......
<?php
include 'connect.php';
$user_id = $_GET["userid"];
$query = mysql_query("SELECT verify,key FROM users WHERE id = '$user_id'");
while ($details = mysql_fetch_assoc($query)){
$verify = $details['verify'];
$confirm2 = $details['key'];
}
if($verify == "1"){
echo "Link Expired . Go to our login page :";
}
else{
if (isset($_GET["confr"]) && isset($_GET["userid"]))
{
$confirm1 =$_GET["confr"];
if($confirm1 == $confirm2){
mysql_query("INSERT INTO users (`verify`) VALUES ('1') WHERE id = '$user_id'");
echo "Thank You For Registering with us . Go to your LOGIN PAGE Here ";
}
else {
echo "Invalid link ";
echo "Go to your LOGIN PAGE Here ";
}
} // of if isset
} // of else part
?>
Note: insert statement has no where - as long as you dont use "insert into select..."
http://dev.mysql.com/doc/refman/5.1/de/insert.html

PhP - username and password validation works, however, clearing out other rows

I have a html page with the form log-in with username and password. When people enter the correct password, it will take them to the php page with their bills. If the password is incorrect, it will display the error message and then exit the program. I got the log-in function to work. However, it's also effecting my other program. Now every time i try to write something in the item/amount row, it also display the error message and exit the program. I know it has something to do with the $numresult>0 condition. When i took that condition out, my amount/item rows work, but the log-in page also allow blank entry in username/password to log in. Any idea how i can make sure that people have to enter the correct password (not a blank entries) to log in, at the same time, get my item/amount rows in the second page behave as normal? My codes are below. Sorry it's a little long.
</head>
<body style="font-family: Arial, Helvetica, sans-serif; color: black;" onload=>
<h1>My Bills</h1>
<form method=post>
<?php
//*************************************************
//Connect to Database
//*************************************************
//*************************************************
//Verify password and username
//*************************************************
$password = $_POST['password']; //retrieve variables for password and userId
$userid = $_POST['userid'];
$query = "SELECT * FROM valid_logon WHERE userid = '$userid' AND
password='$password'"; //get query from database
$result = mysql_query($query);
$numresults = mysql_num_rows($result); //get row number
$row = mysql_fetch_array($result); //get array into variable
$dbuserid = $row['userid'];
$dbpassword = $row['password'];
if ($numresults>0)
{
if ($userid == $dbuserid && $password == $dbpassword)
{
process();
}
}else{
err_msg();
}
//*************************************************
//Error message.
//*************************************************
function err_msg()
{
print "The username and/or password you have entered are invalid.";
print "</body>";
print"</html>";
exit;
}
//*************************************************
//Write out records with data if they exist.
//*************************************************
function process()
{
print "<table>";
print "<tr><th>Item</th><th>Amount</th></tr>";
$action = $_POST['action'];
if ($action == 'update')
{
$write_ctr = 1;
// Delete all rows in the table
$query = "DELETE FROM n1417_expenses ";
$result = mysql_query($query);
if (mysql_error()) {
echo("<br>MySQL Error - Cannot delete from table: ".mysql_error());
echo("<br>SQL Statement: ".$query);
}
// Loop through table and insert values into the database
while (true)
{
$item_name = 'item'."$write_ctr";
$item_value = $_POST[$item_name];
$amount_name = 'amount'."$write_ctr";
$amount_value = $_POST[$amount_name];
if (empty($item_value))
{
break;
}
// Insert an item to the table
if(!is_numeric($amount_value))
{
print "<font color=red>I'm sorry, amount \"".$amount_value."\" is not a valid number.</font><br>\n";
}else{
$query = "INSERT INTO n1417_expenses (item, amount)
VALUES('".$item_value."','".$amount_value."') ";
$result = mysql_query($query);
}
if (mysql_error())
{
echo("<br>MySQL Error - Cannot insert a row into table: ".mysql_error());
echo("<br>SQL Statement: ".$query);
}
$write_ctr++;
}
}
//*************************************************
//Now Select from table and Display
//*************************************************
$err_cnt = 0;
$read_ctr = 1;
$query = "SELECT item, amount FROM n1417_expenses ";
$result = mysql_query($query);
if (mysql_error()) {
echo("<br>MySQL Error- Cannot select from table: ".mysql_error());
echo("<br>SQL Statement: ".$query);
}
if (!empty($result))
{
$rowresults = mysql_num_rows($result);
if ($rowresults > 0)
{
for ($read_ctr=1; $read_ctr<=$rowresults; $read_ctr++)
{
$row = mysql_fetch_array($result);
$item_value = $row['item'];
$item_name = 'item'."$read_ctr";
$amount_value = $row['amount'];
$amount_name = 'amount'."$read_ctr";
print "<tr>";
print "<td><input type=text name=$item_name value='$item_value'></td>\n";
print "<td><input type=text name=$amount_name value='$amount_value'></td>\n";
print "<td>";
print "</tr>";
$total_amt = $total_amt + $amount_value;
}
}
}
//*************************************************
//Now write the blank lines
//*************************************************
for ($i = $read_ctr; $i < $read_ctr + 2; $i++)
{
$item_name = 'item'."$i";
$amount_name = 'amount'."$i";
print '<tr>';
print "<td><input type=text name=$item_name value=''></td>\n";
print "<td><input type=text name=$amount_name value=''></td>\n";
print '</tr>';
}
print "</table>";
print "<br>Total Bills: $total_amt";
}
?>
<br><input type=submit value=Submit>
<br<br>
<!-- Hidden Action Field -->
<input type=hidden name=action value=update>
</form>
To answer the question posted, your problem appears to be that the username and password being are checked again when your user submits the form. Because the fields don't exist, the query finds zero rows, triggering your error message.
There are a number of ways of fixing your problem, one way would be to use a Session to remember that a user is logged in. This could be implemented by altering your password check as follows:
session_start();
if (!isset($_SESSION['logged_in']) || !$_SESSION['logged_in'])
{
$password = $_POST['password']; //retrieve variables for password and userId
$userid = $_POST['userid'];
$query = "SELECT * FROM valid_logon WHERE userid = '".mysql_real_escape_string($userid)."' AND
password='".mysql_real_escape_string($password)."'"; //get query from database
$result = mysql_query($query);
$numresults = mysql_num_rows($result); //get row number
$row = mysql_fetch_array($result); //get array into variable
$dbuserid = $row['userid'];
$dbpassword = $row['password'];
if ($numresults>0)
{
if ($userid == $dbuserid && $password == $dbpassword)
{
$_SESSION['logged_in'] = TRUE;
process();
}
}else{
err_msg();
}
}
I've kept the code as similar to the original as possible, but I will echo the comments above on the need to secure your SQL calls. Have a look at using PDO if possible, or at the very least start using mysql_real_escape_string as above.

Can't find the friend's id to store it to the database

I'm really struggling with this now for a while and can't seem to get it working. In members.php (where I show all the registered users) I have a list printed out with a link "ADD TO FRIENDS" next to each user.
I managed, for testing purposes to display each members id well (so it gets the ID) but when I click the link it directs to the friends.php where it seems the fault is in. I don't know how to get that friend's id I clicked on IN THE friends.php file. Please have a look!
members.php
<?php
include 'connect.php';
include 'header.php';
if(isset($_SESSION['signed_in']) == false || isset($_SESSION['user_level']) != 1 )
{
//the user is not an admin
echo '<br/>';
echo 'Sorry! You have to be <b>logged in</b> to view all the <b>registered</b> members.';
echo '<br/><br/>';
}
else
{
echo '<h2>Registered users:</h2>';
$sql = "SELECT * FROM users ORDER BY user_name ASC";
$result = mysql_query($sql);
$num=mysql_numrows($result);
$i=0;
while ($i < $num)
{
//$name = mysql_result($result,$i,"user_name");
//$id = mysql_result($result,$i,"user_id");
//$picture = mysql_result($result,$i,"pic_location");
//?friend_id="'. $id .'
while($user = mysql_fetch_array($result)){
echo $user['user_name'].'<br/><br/>ADD TO FRIENDS<br/>';
echo $user['user_id'];
echo '<br/><br/>';
}
$i++;
}
///////////////////////////////
/// adding users as friends ///
///////////////////////////////
//while($user = mysql_fetch_array($result))
//echo $user['user_name'].'
//ADD TO FRIENDS<br/>';
//NOW I WANT TO MAKE A SPECIFIC "ADD AS FRIEND" LINK NEXT TO EACH USER
}
include 'footer.php';
?>
As I said I'm not sure how to get this so please have a look! Thanks!
J
friends.php
<?php
include "connect.php";
include "header.php";
if(isset($_SESSION['signed_in']) == false || isset($_SESSION['user_level']) != 1 )
{
//the user is not an admin
echo '<br/>';
echo 'Sorry! You have to be <b>logged in</b> if you want to add the person as a friend!';
echo '<br/><br/>';
}
else
{
$sql = "SELECT * FROM users";
$result = mysql_query($sql);
//friend_id is the ID of the friend that is clicked on...
//HOW DO I GET THAT ID THAT IS CLICKED ON IN THE WHILE "loop" in members.php?
$friends = ("INSERT INTO friends SET user_id='" . $_SESSION['user_id'] . "', friend_id='".$id."', status='0'");
$result_friends = mysql_query($friends);
if(!$friends)
{
//When you can't add this person as a friend this error will show!
echo 'You cannot add this user at this time. Please try again later!';
}
else
{
//When the friend is now added to the system!
echo 'Great! Now the user needs to approve before you can be friends!';
}
}
?>
On your friends.php use
$_GET['user_id']
Instead of $id, $id is undefined, to get the value of id from the query string you call it using an $_GET variable like,
$_GET['name_of_query_string_value']

Categories