validation php not working? - php

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

Related

employee daily sales submission form with respect to ID

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

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!';
}
}
?>

passing and receiving string variables using php

I am passing the string value through link in the URL to the next page like this <a href="ApplicationRegister.php?plan=trial">
In the ApplicationRegister.php page, i am getting this value like this $plan = $_GET["plan"];
and i will put this into a session variable like this $_SESSION['plans'] = $plan;
Here i am getting the value. but after the if statement i am not getting the value for this plan even after using Session variable.
My complete code is like this
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plan'] = $plan;
$plans = $_SESSION['plan'];
echo $_SESSION['plans'];
include('connect.php');
If (isset($_POST['submit']))
{
$CompanyName = $_POST['CompanyName'];
$CompanyEmail = $_POST['CompanyEmail'];
$CompanyContact = $_POST['CompanyContact'];
$CompanyAddress = $_POST['CompanyAddress'];
$StoreName = $_POST['StoreName'];
echo $plans;
$myURL ="$_SERVER[HTTP_HOST]";
$myURL =$StoreName.'.'.$myURL;
if (stripos($myURL, 'www.') !== 0) {
$myURL = 'www.' . $myURL;
}
if (stripos($myURL, 'http://') !== 0) {
$myURL = 'http://' .$myURL;
}
if(stripos($myURL, '.com') !== 0) {
$myURL = $myURL . '.com';
}
echo $plans;
$RegistrationType = $_POST['RegistrationType'];
$Status = "Active";
$sql = "select * from plans where planname = '$plans'";
echo $sql;
mysql_query($sql) or die (mysql_error());
$planID = $row['planid'];
$query1 = "select count(CompanyEmail) from ApplicationRegister where CompanyEmail = '$CompanyEmail'" ;
$result1 = mysql_query($query1) or die ("ERROR: " . mysql_error());
$msg = "";
while ($row = mysql_fetch_array($result1))
{
if($row['count(CompanyEmail)'] > 0)
{
$msg = "<font color='red'> <b>This E-mail id is already registered </b></font> ";
break;
}
}
if($msg == "")
{
$query2 = "select count(URL) from ApplicationRegister where URL = '$myURL' ";
$result2 = mysql_query($query2) or die ("ERROR: " . mysql_error());
$msg = "";
while ($row = mysql_fetch_array($result2))
{
if($row['count(URL)'] > 0)
{
$msg = "<font color='red'> <b>This Stroename is already registered </b></font> ";
break;
}
}
if($msg == "")
{
$sql = "INSERT INTO ApplicationRegister(planid, CompanyName, CompanyEmail, CompanyContact, CompanyAddress, RegistrationType, ApplicationPlan, ApplicationStatus, URL, CreatedDate) VALUES ('$planID', '$CompanyName', '$CompanyEmail', '$CompanyContact', '$CompanyAddress', '$RegistrationType', '$plans', '$Status', '$myURL', NOW() )";
mysql_query($sql) or die(mysql_error());
$id = mysql_insert_id();
$_SESSION['application_id'] = $id;
if($plans == "trail")
{
header("Location: userRegister.php");
exit();
}
else
{
header("Location : PaymentGateway.php");
exit();
}
}
}
}
?>
Only in the beginning it holds the value , if i try to display it within theIf (isset($_POST['submit'])) it shows blank value for plans. Do not know what to do. Plz suggest
EDITED
Even after using like this, its the same. i do not know what may be the problem :(
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plans'] = $plans;
echo $_SESSION['plans'];
// $plan = +$plan;
include('connect.php');
If (isset($_POST['submit']))
{
$CompanyName = $_POST['CompanyName'];
$CompanyEmail = $_POST['CompanyEmail'];
$CompanyContact = $_POST['CompanyContact'];
$CompanyAddress = $_POST['CompanyAddress'];
$StoreName = $_POST['StoreName'];
echo $_SESSION['plans'];
EDITED
In ApplicationRegister.php, i have passed the hiddenvalue which i got fro\m previous page like this
<input type="hidden" name="plan" value="<?php echo $plan ?>"/>
then POST method i have used this. Now i am getting the value for it. Thanks to all
EDITED
if($PlanName == "trail")
{
header("Location: userRegister.php");
exit();
}
else
{
header("Location : PaymentGateway.php");
exit();
}
It's because you're not calling session_start() at the top of the page. You need that for your sessions to persist across requests (which is the point of sessions)
As well as not calling session_start();, this code is wrong:
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plan'] = $plan;
$plans = $_SESSION['plan'];
echo $_SESSION['plans'];
It should be:
$plan = $_GET["plan"];
echo $plan;
$_SESSION['plan'] = $plan;
$plans = $_SESSION['plans'];
echo $_SESSION['plans'];
You are setting $_SESSION['plan'] and then trying to access $_SESSION['plans'].
Also, are you clicking a link or submitting a form? You say that you have a link, yet your code tries to access values passed from a form.
If you are using a form, don't use links. Instead, use a select element to select a plan, and then change $plan = $_GET["plan"]; to $plan = $_POST["plan"];.
EDIT:
For the redirection problem, try this code:
echo "<pre>** Plan Name: **\n";
var_dump($PlanName);
echo "</pre>";
if($PlanName == "trail")
{
header("Location: userRegister.php");
exit();
}
else
{
header("Location: PaymentGateway.php");
exit();
}
and see what it outputs.
When someone clicks the link, it's going to set the variable properly. However, it's not going to hit the $_POST['submit'] logic, because it's not a post, just a get. Then, assuming your actually posting to that page at a later point, trying to access anything in $_GET will be null, and will then reset the session variable to null.
Your first page should have code something like this
<form action="ApplicationRegister.php" method="post">
<select name="plan">
<option value="trial">Trial</option>
</select>
<input type="submit"/>
</form>
Then, you check for $_POST['plan'] and $_POST['submit']

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']

refresh problem in online users list

I have a problem with the online users list.
The code works fine, all the online users are displayed on the screen but when I click on refresh, the same user's email is displayed again and when I click on refresh for the second time the user's email is displayed three times and so on.
Here is my code:
<?php
require_once("db.php");
db_connect();
session_start();
$player_timeout = time() - 5 * 60;
$time = time();
if (isset($_SESSION['email'])) {
$login=mysql_query("insert into activePlayer(player_email,time_visited,status) values('".$_SESSION['email']."','".$time."', 'true')");
}
else
{echo "You are not logged in";}
$tmout = mysql_query("DELETE FROM activePlayer WHERE time_visited < ".$player_timeout);
$online_member = mysql_query("SELECT player_email FROM activePlayer");
$row=mysql_num_rows($online_member);
$member_row=mysql_fetch_array($online_member);
echo "Welcome '".$_SESSION['email']."'";
?>
<body>
<select > <?php
if ($row<1)
{
echo " ";
}
else
{?> <p><p>Online Players:<option><?php echo $member_row['player_email'];?>
</option>}
<?php for ($i=1;$i<$row;$i++)
{
$member_row=mysql_fetch_array($online_member);?>
<p><p>Online Players:<option><?php echo $member_row['player_email']; }}?>
</option></select>
</body>
please how can I solve this problem
Every time you refresh you insert a row into the db if the user is logged in. You have to check if the user already exists in the db and update his record instead. If he has no record then just create a new as you do.
$hasRow = mysql_query("SELECT * FROM activePlayer WHERE player_email='".$_SESSION['email']."' LIMIT 1");
if(mysql_num_rows($hasRow) > 0) {
$login = mysql_query("UPDATE activePlayer SET visited=".time()." WHERE player_email='".$_SESSION['email']."'");
} else {
$login=mysql_query("insert into activePlayer(player_email,time_visited,status) values('".$_SESSION['email']."','".$time."', 'true')");
}
What you need to do is a redirect:
if (isset($_SESSION['email'])) {
mysql_query("INSERT INTO activePlayer (player_email,time_visited,status)
VALUES ('".$_SESSION['email']."','".$time."', 'true')");
unset($_SESSION['email']);
header("Location: otherpage.php"); // or it can be the same page
}

Categories