registration not working in php - php

hi i am trying to create a registration page using html and php and the database is mysql. the IDE i am using is cloud9. the code for my form is as follows:
<form action="signup_code.php" method="post">
<p>Name<br/><input type="text" name="name" maxlength="20" ></p>
<p>Phone Number<br/><input type="number" name="phone" maxlength="20" ></p>
<p>Email<br/><input type="email" name="email" maxlength="50" ></p>
<p>Password<br/><input type="password" name="pass1" maxlength="20" ></p>
<p>Confirm Password<br/><input type="password" name="pass2" maxlength="20" ></p>
<p>Address<br/><input type="text" name="address" maxlength="20" ></p>
<button type="submit" class="btn btn-default">Signup
</button>
</form>
the code in the signup_code .php is :
<?php
$IP = "0.0.0.0";
$dbuser = "bhaskey";
$conn = mysqli_connect($IP, $dbuser, "","trydb");
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
$address = $_POST['address'];
$query = "SELECT email FROM user_main where email='".$email."'";
$result = mysqli_query($conn,$query);
$numResults = mysqli_num_rows($result);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) // Validate email address
{
$message = "Invalid email address please type a valid email!!";
}
elseif($numResults>=1)
{
$message = $email." Email already exist!!";
}
else
{
mysqli_query("(insert into user_main(name,phone, email,pass1, pass2, address) values
('".$name."','".$phone."', '".$email."', '".pass1."','",$pass2."','".$address."')");
echo $message = "Signup Sucessfully!!";
}
mysqli_close($conn);
?>
however when i am executing the the code i.e clicking the signup button in the form, it is giving me the following result
"Cannot POST /bhaskey/eshopper/signup_code.php"
where i am going wrong. i am sure it must be a silly mistake. but since i am pretty new and still in learning phase, it is becoming troublesome for me.
EDIT: i tried to pass the whole path of the .php file to the action in form. but after i click on the submit button, the page turns whte and nothing is displayed anymore.
i tried clearing browser cache but its not helping.

You have to replace your this code
$conn = mysql_connect($IP, $dbuser, "","trydb");
to this code
$conn = new mysqli($IP, $dbuser, "","trydb");
and also replace this code
mysql_close($conn);
to this code
mysqli_close($conn);

$IP = "0.0.0.0";?
Instead you should use 'localhost' or possibly 127.0.0.1.

Related

Register Form PHP not inserting values into DB, just reloading the page

I really can not find what am I doing wrong in my registration form, unfortunately the page is just reloading instead of inserting values from form to my DB table.
Register.php
<?php
require_once("./Connection.php");
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$options = array("cost"=>5);
$hashPassword = password_hash($password,PASSWORD_BCRYPT,$options);
$sql = "insert into agents (firstName, lastName, email, phone, password) value ('".$firstName."', '".$lastName."', '".$email."','".$phone."','".$hashPassword."')";
$result = mysqli_query($conn, $sql);
if($result)
{
echo "Registration successfully";
}
}
?>
Connection.php
<?php
$conn = mysqli_connect("localhost","root","","KBHestate");
if(!$conn){
die("Connection error: " . mysqli_connect_error());
}
Register Form
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<input type="text" name="firstName" value="" placeholder="First Name">
<input type="text" name="lastName" value="" placeholder="Surname">
<input type="text" name="email" value="" placeholder="Email">
<input type="text" name="phone" value="" placeholder="Phone">
<input type="password" name="password" value="" placeholder="Password">
<button type="submit" name="submit">Submit</button>
</form>
Please make sure the following line has no problem when it is interpreted by the PHP:
$options = array("cost"=>5);
$hashPassword = password_hash($password,PASSWORD_BCRYPT,$options);
On the other hand, please make sure that the password field is wide enough to store the $hasPassword data
Your code looks fine, it should work. I am hoping you are having Register form in the same file Register.php
But as you mentioned it's just reload the page that means there must be a exception/error from mysql query that is not handled in your code.
You have not shared your table structure. So, I am answering you based on the common mistake.
Like one of your table column width is varchar(10) and you are trying to pass data of length 20 char.
So, i suggest you to add below code in your Register.php as the else condition for if($result). So, it will display the error if any.
else {
echo("Error description: " . $conn->error);
}
Now your Register.php code will be look like below:
<?php
require_once("./Connection.php");
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$options = array("cost"=>5);
$hashPassword = password_hash($password,PASSWORD_BCRYPT,$options);
$sql = "insert into agents (firstName, lastName, email, phone, password) value ('".$firstName."', '".$lastName."', '".$email."','".$phone."','".$hashPassword."')";
$result = mysqli_query($conn, $sql);
if($result)
{
echo "Registration successfully";
}else {
echo("Error description: " . $conn->error);
}
}
?>

PHP code filed checking logical error and creating duplicate entries

my code generating fetal error in the code it check all fields except cnic filed, a cnic already exist in table in multiple rows.When we try to create login for new member with same cnic it create duplicate entry rather to checking and generate error for the already exiting cnic. i mean to say it check both email and cnic if both exit it deny for new registration but in my case some time it check and some time it not check the email and cnic. Please correct my code i try a lot but i am unable to filed where i'm doing wrong.Your help in this regard will highly helpful for me and i will be highly thankful to you.
<?php
//Start the Session
require_once("config.php");
//error_reporting(0);
$headers ='';
$res = '';
$Message = '';
$Message1 = '';
$Message2 = '';
$recaptcha = '';
$query ="SELECT * FROM tbl_signup;";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
$user_cnic = $row['apli_cnic'];
$User_Email = $row['apli_email'];
if(isset($_POST['ButtonSignUp']))
{
$Cnic=mysqli_real_escape_string($conn, $_POST['cnic']);
$Name= mysqli_real_escape_string($conn,$_POST['namesurname']);
$Email = mysqli_real_escape_string($conn, $_POST['email']);
$Password = mysqli_real_escape_string($conn, $_POST ['password']);
$CnfrmPassword = mysqli_real_escape_string($conn, $_POST['confirmPassword']);
$ActivationCode = md5( rand(0,1000) );
$Status = 0;
if ($Cnic == $user_cnic)
{
$Message = "Sign Up Failed. Account With CNIC: $user_cnic Already Exist";
}
elseif($Email == $User_Email)
{
$Message1 = "$Email Already Exist. Please Enter Another Email Address.";
}
elseif($Password != $CnfrmPassword)
{
$Message2 = "Your Password does not match the Confirm Password";
}
elseif ($Password == $CnfrmPassword)
{
$sql= "INSERT INTO table(fname, email, cnic, pwd, cnfrm_pwd, activation_code, status)
VALUES ('$Name','$Email','$Cnic','$Password','$CnfrmPassword', '$ActivationCode', '$Status');";
mkdir("DocumentUpload/$Cnic");
$to_email = $Email;
$subject = 'Verify Your Email';
$message = "Your account information is successfully updated. Please click the following link For verifying and activate your account.
$headers = 'From: abc.com
$res = mysqli_query($conn, $sql);
if(mail($to_email, $subject, $message, $headers))
{
}
}
if($res == 1)
{
header("location:VerifyEmailWait.php");
}
else
{
}
}
mysqli_close($conn);
?>
<form id="sign_up" method="POST">
<input type="number" class="form-control" name="cnic" placeholder="CNIC e.g. 3520212345678" maxlength="13" required autofocus autocomplete="off">
<input type="text" class="form-control" name="namesurname" placeholder="Full Name (As Per CNIC)" required autofocus autocomplete="off">
<input type="email" class="form-control" name="email" placeholder="Email Address" required autocomplete="off">
<input type="password" class="form-control" name="password" id="password" minlength="8" placeholder="Password" required autocomplete="off">
<input type="password" class="form-control" name="confirmPassword" id="confirmPassword" minlength="8" placeholder="Confirm Password" required autocomplete="off">
<button class="btn btn-block btn-lg bg-pink waves-effect" type="submit" name="ButtonSignUp">SIGN UP</button>
Already a Member? Please Sign In
</form>
Your insert statement
INSERT INTO table(fname, email, cnic, pwd, cnfrm_pwd, activation_code, status)
VALUES ('$Name','$Email','$Cnic','$Password','$CnfrmPassword', '$ActivationCode', '$Status');
is wrong it must be
INSERT INTO tbl_signup(fname, email, cnic, pwd, cnfrm_pwd, activation_code, status)
VALUES ('$Name','$Email','$Cnic','$Password','$CnfrmPassword', '$ActivationCode', '$Status');
Where you use the proper tabke name a generic table like you did is not allowed.
But please read this about passwords
And of course that about preventing sql injection
Before you proceed in your development.

Joining two strings to create one variable in php

Ok so I have a registration form for users to register and it works fine in that when it submits it enters into my database. I want to add a feature that only users with a certain domain address can register and after looking this up the simplest way I can see to do it is to use a drop down menu with a list of the available domains accepted. My issue is that when I try and run the concatenation function to join them upon entry they are not being joined and added to the database correctly below is my HTML form and my php code.
<form name='registration' method="post" action="registerAdmin.php">
<label for="adminName"> Name: </label>
<input name="adminName" id="a" size="27" required/>
<br/>
<label for="adminEmail"> Email Address: </label>
<input type="text" name="adminEmail" id="a" size="15" required/> <select style="height:27px;width:5;" name="adminDomain"><option value="#ucc.ie">#ucc.ie</option></select>
<br/>
<label for="adminUsername"> Username: </label>
<input name="adminUsername" id="b" size="27" required/>
<br/>
<label for="password"> Password: </label>
<input type="password" name="adminPassword" id="b" size="27" required/>
<br/>
<br/>
<input id="boo" type="submit" name="button" value="Register" class="btn btn-danger btn-lg"/>
</form>
And my PHP code:
$servername = "localhost";
$username = "********";
$password = "********";
$dbname = "********";
// FORM HANDLING
$aName = $_POST["adminName"];
$aEmail = $_POST["'adminEmail"];
$aUsername = $_POST["adminUsername"];
$aPassword = $_POST["adminPassword"];
$aEmail .= $_POST["adminDomain"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if (mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO administrators (`adminName`, `adminEmail`, `adminUsername`, `adminPassword`)
VALUES ('".$aName."','".$aEmail."','".$aUsername."','".$aPassword."')";
if ($conn->query($sql) === FALSE) {
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
} else {
echo "Account has successfully been created, please click the link below to return to the login screen!";
}
$conn->close();
?>
Everything bar the email address gets entered into the database correctly.
There is an extra "'" in the below statement:
$aEmail = $_POST["'adminEmail"]; it has to be `$aEmail = $_POST["adminEmail"];`
This should sort out the issue.

I can't insert data into my database while in a Session

I have the tables users and register in my database. I've created a login page which starts a session using the users table, then people fill out a form to insert data into the register table. I've used the following code to insert the data. My code doesn't have errors but the thing is it is not inserted to my table. Please help me. Thanks.
<?php
include("includes/db.php");
session_start();
if(!isset($_SESSION['user_name'])){
header("location: login.php");
}
else { ?>
<html>
<body>
<h2>New users Signup!</h2>
<form action="login.php" method="post">
<input type="text" name = "firstname" placeholder="Firstname"/>
<input type="text" name = "lastname" placeholder="Lastname"/>
<input type="text" name = "address" placeholder="Address"/>
<input type="text" name = "contact" placeholder="Contact"/>
<input type="text" name = "email" placeholder="Email Address"/>
<input type="password" name = "password" placeholder="Password"/>
<div class = "bttn">
<button type="submit" name = "submit" class="btn btn-default">Signup</button>
</div>
</form>
</body>
</html>
<?php
if(isset($_POST['submit']))
{
$users_firstname = $_POST['firstname'];
$users_lastname = $_POST['lastname'];
$users_address = $_POST['address'];
$users_contact = $_POST['contact'];
$users_email = $_POST['email'];
$users_password = $_POST['password'];
$users_date = date('Y-m-d');
if($users_firstname=='' or $users_lastname=='' or $users_address=='' or $users_contact=='' or $users_email=='' or $users_password=='')
{
echo "<script>alert('Any of the fields is empty')</script>";
exit();
} else {
$insert_query = mysql_query("insert into users (users_firstname,users_lastname,users_address,users_contact,users_email,users_password,users_date) values ('$users_firstname','$users_lastname','$users_address','$users_contact','$users_email','$users_password','$users_date')");
$users_id=mysql_insert_id();
if(mysql_query($insert_query)) {
echo "<script>alert('post published successfuly')</script>";
}
}
}
} ?>
Now try this code:
<?php
include("includes/db.php");
session_start();
if(!isset($_SESSION['user_name'])){
header("location: login.php");
}
else {
?>
<html>
<body>
<?php
if(isset($_POST['submit']))
{
$users_firstname = $_POST['firstname'];
$users_lastname = $_POST['lastname'];
$users_address = $_POST['address'];
$users_contact = $_POST['contact'];
$users_email = $_POST['email'];
$users_password = $_POST['password'];
$users_date = date('Y-m-d');
if($users_firstname=='' or $users_lastname=='' or $users_address=='' or $users_contact=='' or $users_email=='' or $users_password=='')
{
echo "<script>alert('Any of the fields is empty')</script>";
exit();
}
else
{
$insert_query = mysql_query("INSERT INTO `users` (users_firstname, users_lastname, users_address, users_contact, users_email, users_password, users_date) values ('$users_firstname', '$users_lastname', '$users_address', '$users_contact', '$users_email', '$users_password', '$users_date')");
$users_id=mysql_insert_id();
echo "<script>alert('post published successfuly')</script>";
}
}
?>
<h2>New users Signup!</h2>
<form action="" method="post">
<input type="text" name="firstname" placeholder="Firstname"/>
<input type="text" name="lastname" placeholder="Lastname"/>
<input type="text" name="address" placeholder="Address"/>
<input type="text" name="contact" placeholder="Contact"/>
<input type="text" name="email" placeholder="Email Address"/>
<input type="password" name="password" placeholder="Password"/>
<div class="bttn">
<button type="submit" name="submit" class="btn btn-default">Signup</button>
</div>
</form>
</body>
</html>
<?php } ?>
I have:
Repositioned your PHP code for inserting to be at the top of the form
changed <form action="login.php" to <form action="" because we are executing from the same page
Your query has already run so removed the if(mysql_query...
Removed the spaces in the form e.g. name = " nameofform" to name="nameofform"
I don't see any reason for having this $users_id=mysql_insert_id();, YOu should use auto-increment for the userID on your database
But since we don't know how you have connected to your database, because also that can be an issue: you can also try this way
<?php
//connect to DB
$hostname_localhost = "localhost"; //hostname if it is not localhost
$database_localhost = "databasename";
$username_localhost = "root"; //the username if it is not root
$password_localhost = "password_if_any"; //if no password leave empty
$localhost = mysql_pconnect($hostname_localhost, $username_localhost, $password_localhost) or trigger_error(mysql_error(),E_USER_ERROR);
?>
<?php
// include("includes/db.php");
if (!isset($_SESSION)) {
session_start();
}
if(!isset($_SESSION['user_name'])){
header("location: login.php");
}
else {
?>
<html>
<body>
<?php
if(isset($_POST['submit']))
{
$users_firstname = $_POST['firstname'];
$users_lastname = $_POST['lastname'];
$users_address = $_POST['address'];
$users_contact = $_POST['contact'];
$users_email = $_POST['email'];
$users_password = $_POST['password'];
$users_date = date('Y-m-d');
if($users_firstname=='' or $users_lastname=='' or $users_address=='' or $users_contact=='' or $users_email=='' or $users_password=='')
{
echo "<script>alert('Any of the fields is empty')</script>";
exit();
}
else
{
$insert_query = sprintf("INSERT INTO `users` (users_firstname, users_lastname, users_address, users_contact, users_email, users_password, users_date) values ('$users_firstname', '$users_lastname', '$users_address', '$users_contact', '$users_email', '$users_password', '$users_date')");
mysql_select_db($database_localhost, $localhost);
$Result = mysql_query($insert_query, $localhost) or die(mysql_error());
echo "<script>alert('post published successfuly')</script>";
}
}
?>
<h2>New users Signup!</h2>
<form action="" method="post">
<input type="text" name="firstname" placeholder="Firstname"/>
<input type="text" name="lastname" placeholder="Lastname"/>
<input type="text" name="address" placeholder="Address"/>
<input type="text" name="contact" placeholder="Contact"/>
<input type="text" name="email" placeholder="Email Address"/>
<input type="password" name="password" placeholder="Password"/>
<div class = "bttn">
<button type="submit" name="submit" class="btn btn-default">Signup</button>
</div>
</form>
</body>
</html>
<?php } ?>
You should removed the whitespaces in your html-code:
Wrong
<input type="text" name = "firstname" placeholder="Firstname"/>
^^^^^
Correct
<input type="text" name="firstname" placeholder="Firstname"/>
Do not put the variables in single quotes:
$insert_query = mysql_query("INSERT INTO users
(users_firstname,users_lastname,users_address,users_contact,users_email,users_password,users_date)
VALUES
($users_firstname,$users_lastname,$users_address,$users_contact,$users_email,$users_password,$users_date)");
Update: This was wrong. The whole string is in double-quotes so the OP did correct and my notice was wrong. For information-purposes i will let stand the link to the documentation here.
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
Read more about single- and double-quotes in the PHP documentation.
Do not double-run the query/perform wrong function-call
$insert_query = mysql_query(".......");
........
if(mysql_query($insert_query)){
echo "<script>alert('post published successfuly')</script>";
}
You already have run the query in the first line. If you want to check if it was successful, you have to use if($insert_query) {}. The call mysql_query($insert_query) is wrong because mysql_query() returns a ressource instead of the sql-query.
Do not use mysql_*() function calls. You mysqli_*() instead.
Warning
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_query()
PDO::query()
Check your use of session.
You are checking the $_SESSION for user_name and if it is not set, you are redirecting via header("location: login.php").
The problem is, that you are never inserting the user_name into the session, so it will always be not set.
You can set the value via $_SESSION['user_name'] = $_POST['user_name']. Have in mind that you have to set the session before checking the session-value. ;-)
remove action
Try this
<form action="" method="post">

PHP: Simple form to posts to database

I've been so out of touch with using PHP outside of content management systems that I've forgot some of the basic syntax etc. What I'm trying to build is a simple form that collects some user data and sends it to a database table called 'creathive_applications'.
Here is my HTML form:
<form action="<?php bloginfo('home'); ?>" method="post">
<fieldset id="membershipform">
<ul class="clearfix">
<li id="li-status">
<span>I am a:</span>
<menu>
<li><label for="student"><input disabled="disabled" type="radio" name="status" id="student" checked="checked" value="Graduate" /> Graduate</label></li>
<li><label for="student2"><input disabled="disabled" type="radio" name="status" id="student2" value="Undergraduate" /> Undergraduate</label></li>
</menu>
</li>
<li id="li-firstname">
<label for="firstname">First Name</label> <input name="firstname" disabled="disabled" type="text" placeholder="First Name" id="firstname" title="First Name" />
</li>
<li id="li-lastname">
<label for="lastname">Last Name</label> <input name="lastname" disabled="disabled" type="text" placeholder="Last Name" id="lastname" title="Last Name" />
</li>
<li id="li-email">
<label for="email">Email address</label> <input name="email" disabled="disabled" type="text" placeholder="Email address" id="email" title="Email address" />
</li>
<li id="li-url">
<label for="url">URL</label> <input name="url" disabled="disabled" type="text" placeholder="URL of something you've made" id="url" title="URL of something you've made" />
</li>
<li id="li-buttons">
<input name="submit" type="submit" value="Send Application ►" title="Send Application" onclick="alert('Invites available from March 2011');" />
</li>
</ui>
</fieldset>
</form>
and here is the PHP jazz:
if(isset($_POST['submit']))
{
$status = $_POST['status'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$url = $_POST['url'];
$host = '####';
$username = '####';
$pass = '####';
mysql_connect($host,$username,$pass);
mysql_select_db($username);
$query = "INSERT INTO creathive_applications VALUES (NULL,'".$status."','".$firstname."','".$lastname."','".$email."','".$url."')";
$result = mysql_query($query);
}
Can anyone help me fix this as I can't remember how to run my SQL statement and send the data to the database :/ Also I've added the database username and password as well as host but what about the database name? Where does that go again?
I know this is a rather n00b question, but any help would be much appreciated.
THANKS A LOT
Well, with no error it's impossible to tell what to fix.
However, there are some obvious things to do.
See the comments:
<?
//show all possible errors. should be ALWAYS set to that level
error_reporting(E_ALL);
echo "landed at form handler<br>";
// sometimes buttons not being sent or gets misspelled
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
echo "here goes POST processing<br>";
$host = '####';
$username = '####';
$pass = '####';
mysql_connect($host,$username,$pass);
mysql_select_db($username);
// all strings should be escaped
// and it should be done after connecting to DB
$status = mysql_real_escape_string($_POST['status']);
$firstname = mysql_real_escape_string($_POST['firstname']);
$lastname = mysql_real_escape_string($_POST['lastname']);
$email = mysql_real_escape_string($_POST['email']);
$url = mysql_real_escape_string($_POST['url']);
$query = "INSERT INTO creathive_applications
VALUES (NULL,'$status','$firstname','$lastname','$email','$url')";
echo $query;
// always run your queries this way to be notified in case of error
$result = mysql_query($query) or trigger_error(mysql_error().". Query: ".$query);
var_dump($result);
}
in case you still see no error, add this line temporarily to the top of the script
ini_set('display_errors',1);
and remove it immediately after you get the problem solved.
EDIT
added some debug info.
If you see none of it's messages, you're sending your form to the wrong URL.
If you see some of them, post it here
As Brian noted, you should post if any errors are happening.
The main thing I notice is that you are using variables that potentially have no values. Radio buttons do not send their values if they are not toggled.
Use something like this to cover your bases:
if(isset($_POST['status']))
{
$status = $_POST['status'];
}
Don't know if that's your problem. Consider adding more information. :)
if(count($_POST) > 0){
$status = $_POST['status'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$url = $_POST['url'];
$host = '####';
$username = '####';
$pass = '####';
$mydb = mysql_connect($host,$username,$pass);
// mysql_select_db($username);
//are you using your username as db name?
mysql_select_db("yourdbname");
$query = "INSERT INTO creathive_applications VALUES (NULL,'".mysql_real_escape_string($status)."','".mysql_real_escape_string($firstname)."','".mysql_real_escape_string($lastname)."','".mysql_real_escape_string($email)."','".mysql_real_escape_string($url)."')"; //use mysql_real_escape_string for security
$result = mysql_query($query);
//show error if query fails.
if (!$result) {
die('Invalid query: ' . mysql_error());
}
mysql_close($mydb); //close the connection
}
add the mysql_error(); and see if it prints out errors

Categories