I am trying to create a user registration form using php and mysql. When I try to hit the submit button no new record is added to my database. The database is functional and has worked with other forms.
HTML/FORM
<?php
include 'header.php';
?>
<section>
<div class="form">
<form action="signup.php" method="post">
<h1> Sign Up!</h1>
<p>First name:
<input type="text" name="fName" maxlength="15" required pattern="^[a-zA-Z]{3,20}$" placeholder="Enter Name" />
</p>
<p>Last name:
<input type="text" name="lName" maxlength="15" pattern="^[a-zA-Z]{3,20}$" required placeholder="Enter Last Name" />
</p>
<p>Email:
<input type="email" name="email" maxlength="40" required placeholder="Enter Email" />
</p>
<p>Username:
<input type="text" name="username" maxlength="20" ^[A-Za-z0-9_]{1,15}$ required placeholder="Enter Username" />
</p>
<p>Password:
<input type="password" name="password" maxlength="20" pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" required placeholder="Enter Password" />
</p>
<p>Re-type Password:
<input type="password" name="password2" maxlength="20" pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$" required placeholder="Re-type Password" />
</p>
<p>
<button type="submit" name="signupbutton"> Sign up </button>
</p>
</form>
</div>
</section>
<div class="footerspecial">
<?php
include 'footer.php';
?>
</div>
PHP/SQL
<?php
//have they submitted at least once?
if(isset($POST['$password2'])){
$fName = $_POST['fName'];
$lName = $_POST['lName'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
//do the passwords NOT match?
if ($password !== $password2) {//do string comparison here
echo'<h2>Error: passwrods don\'t match!</h2>';
require ('registerform.php');
}
else {
//does the username already exist?
$sql = mysql_query("SELECT * FROM users WHERE username=='$username'");
if ($results=$con->query($sql)){
echo'<h2>Error: username is already taken</h2>';
require ('registerform.php');
}
else {
$sql = mysql_query("SELECT * FROM users WHERE email=='$email'");
if ($results=$con->query($sql)){
echo'<h2>Error: email already used</h2>';
require ('registerform.php');
}
else {
// If the values are posted, insert them into the database.
$sql= "INSERT INTO users (fName, lName, email, username, password, password2) VALUES ('$fName', '$lName', '$email', '$username', '$password', $password2)";
if (!$con->query($sql)){
echo 'Error: coulndt do suff';
}
else {
echo 'Account made';
}//ENDS SUCCESSFUL INSURT
}//ENDS EMAIL VALIDATION
}//ENDS THE USERNAME VALIDATION
}//END PASSWORD VALIDATION
}
?>
Picture of the form don't really know if its helpful but ya'know
https://gyazo.com/418b86ecb5090604a1f229e1e94fe3bf
I'm guessing here that your database doesn't have a password2 column (seems kind of pointless to have) so trying to insert into it will give an error.
You should read about MySQLi error reporting
Also add error_reporting(-1); at the start of your PHP file to show PHP errors.
P.S. your code is vulnerable to SQL injection, you should use prepared statements to be safe from this.
Could have multiple problems first you do not have the single quotes around $password2. This could be leading to a failed insert.
VALUES ('$fName', '$lName', '$email', '$username', '$password', $password2)";
Also I would echo the sql errors out as you are not doing. you can do this easily. Test the if statement for a true not a false
if ($con->query($sql)){
//if true then runs your code;
}
else {
echo "Error: " . $sql . "<br>" . $con->error; // This will echo out any sql errors you may have
}
Related
Hi I am trying to make a registration form that sends input data to phpmyadmin's database I created. I think I mixed up MySQLI and MySQL any suggestions on how to fix would be great!! I just dont understand why my data is not being sent over to the database on phpmyadmin.
PHP:
// connect to database
$db = mysqli_connect("127.0.0.1", "root", "", "user logins");
if (isset($_POST['register_btn'])) {
$firstName = mysql_real_escape_string($_POST['firstName']);
$lastName = mysql_real_escape_string($_POST['lastName']);
$emailAddress = mysql_real_escape_string($_POST['emailAddress']);
$password = mysql_real_escape_string($_POST['password']);
$password2 - mysql_real_escape_string($_POST['password2']);
}
if ($password == $password2) {
// create user
$password = md5($password); //hash password before storing for security
$sql = "INSERT INTO user logins(firstName, lastName, emailAddress, password) VALUES('$firstName', '$lastName' '$emailAddress', '$password')";
mysqli_query($db, $sql);
$_SESSION['message'] = "You are now logged in";
$_SESSION['username'] = $username;
header('location: homepage.html'); //redirect to homepage
} else {
$_SESSION['message'] = "The two passwords do not match";
}
?>
HTML:
<link rel="stylesheet" type="text/css" href="custom.css">
<body class="background">
<div>
<h1 class="header1">Sign in Below</h1>
</div>
<div>
<form action="connect.php" method="post">
<div>
<label for="firstName">First Name:</label>
<input type="text" name="first_name" id="firstName">
</div>
<div>
<label for="lastName">Last Name:</label>
<input type="text" name="last_name" id="lastName">
</div>
<div>
<label for="emailAddress">Email Address:</label>
<input type="email" name="email" id="emailAddress">
</div>
<div>
<label for="password">Password:</label>
<input type="password" name="password" id="password">
</div>
<div>
<label for="password2">Repeat Password:</label>
<input type="password" name="password2" id="password2">
</div>
<input type="submit" name="register_btn" value="register">
</form>
</div>
</body>
Have you put in a password?
Is your database on your local machine?
Is your database table called user logins (with a space)
Is root your login?
Is your PHP file called connect.php?
Any error messages?
What happens when you click the form button
Sorry just a few things that crossed my mind that might help determine the problem.
You may just need to remove the following curly bracket
$password2 - mysql_real_escape_string($_POST['password2']);
}
and add it at the end of you file so it runs with your isset() function
$_SESSION['message'] = "The two passwords do not match";
}
}
?>
I don't think "user logins" is a valid table name. Change it to "user_logins", or at the very least, use the quote ` around the table name.
INSERT INTO `user logins`(
OR
INSERT INTO user_logins(
Second one you have to rename the table in phpmyadmin. As a general rule, you want to quote table names no matter what. Because sometimes your table name is a MySQL-reserved keyword. It's just good practice.
Also, the 4th parameter in mysqli_connect is database name. So is your database named "user logins"? Don't confuse table name with database name.
solved:(a small mistake)
this line is not a assignment :
$password2 - mysql_real_escape_string($_POST['password2']);
to
$password2 = mysql_real_escape_string($_POST['password2']);
( - ) must be converted to (=)
I used this code to create a user registration page in my website. I firstly connected to my database and then did the below codes ----->
<form action="index.php" method="post">
<p id="usr1">Name : </p><input id="input1" placeholder="Username" type="text" name="username" required> </br>
</br>
<p id="usr2">Password : </p><input id="input2" placeholder="Password" type="text" name="pwd" required> </br>
<p id="usr3">Password : </p><input id="input3" placeholder="Re-Type your password" type="text" name="cpwd" required> </br>
</br>
<input id="sub" name="subbox" type="submit">
</form>
<?php
if (isset($_POST['submit_button'])) {
$username= $_POST['username'];
$password=$_POST['pwd'];
$conpwd=$_POST['cpwd'];
}
if ($password == $conpwd) {
$query = "SELECT * FROM login WHERE name='$username' ";
$query_run = mysqli_query($con,$query);
if (mysqli_num_rows($query_run) > 1) {
echo '<script type="text/javascript">alert("This Username Already exists. Please try another username!")</script>';
// the above code will check if the username is already taken or not.
}else {
$query = "insert into login values('$username' , '$password')";
$query_run = mysqli_query($con,$query);
if ($query_run) {
echo '<script type="text/javascript">alert("Registration Successful!")</script>Click Here To Continue';
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header( "Location: homepage.php");
}else {
echo '<script type="text/javascript">alert("Server Error. Please try again after a few minutes!")</script>';
}
}
}else {
echo "Please check and re-type both passwords";
}
?>
But it always return some errors.This is what I see when i try to run the code
Is anything wrong with this code?
To answer your initial question, yes there is something wrong. Your code is vulnerable to SQL injection. You should have a look at: How can I prevent SQL injection in PHP? And password is stored plain in your database, which means no respect for your user. There are some other problems with code style but it's just bonus.
Anyway, the thing that cause you the "alert" problem is that submit_button button does not exists. There is no button with that name. Your if condition is always false. So you have to replace:
if (isset($_POST['submit_button'])) {
With
if (isset($_POST['subbox'])) {
And maybe add a value to your input (not sure it's required, I did not tested):
<input id="sub" name="subbox" type="submit" value="1">
Thanks to #Fred-ii-
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I have an issue with inserting the data that I gather from one of my forms into my database.
Each form adds data to a different table in the database(one into users and one into tasks).
I use one form for registration and I'll paste the important parts of the code below(this one is working).
This is the form part of the Register.php file
<form method="post" action="register_code.php">
<div class="FormElement">
<input name="user_name" type="text" class="Tfield" id="user_name" required placeholder="User Name">
</div>
<div class="FormElement">
<input name="password" type="password" class="Tfield" id="password" required placeholder="Password">
</div>
<div class="FormElement">
<input name="email" type="email" class="Tfield" id="email" required placeholder="E-mail">
</div>
<div class="FormElement">
<input name="first_name" type="text" class="Tfield" id="first_name" required placeholder="First Name">
</div>
<div class="FormElement">
<input name="last_name" type="text" class="Tfield" id="last_name" required placeholder="Last Name">
</div>
<div class="FormElement">
<input type="submit" id="Register" name="Register" value="Register" class="button">
</div>
This is the register_code.php file
<?php
require "DBconnect.php";
$post = $_POST;
if(isset($post)) {
session_start();
$UName = $post['user_name'];
$PW = md5($post['password']);
$FName = $post['first_name'];
$LName = $post['last_name'];
$Email = $post['email'];
$sql = $con->query("INSERT INTO users (user_name, password, email, first_name, last_name) VALUES ('$UName','$PW','$Email', '$FName', '$LName')");
if($sql)
header("Location: Registration_successful.php");
else
echo "Please try again to register";
}
include 'Register.php';
And another form I use to add data into another table(named tasks). The data I gather from this file will not insert into my database for some reason.
This is the form part of the Add_Task.php file:
<form method="post" action="Add_Task_code.php">
<div class="FormElement">
<input name="TName" type="text" class="Tfield" id="TName" required placeholder="Task name">
</div>
<div class="FormElement">
<input name="TDesc" type="text" class="TextField" id="TDesc" required placeholder="Task summary">
</div>
<div class="FormElement">
<input type="submit" id="Submit" name="Submit" value="Submit" class="button">
</div>
</form>
And this is the code from the Add_Task_code.php file
<?php
require 'DBconnect.php';
$post=$_POST;
if(isset($post))
{
$TaskName = $post['TName'];
$TaskDesc = $post['TDesc'];
$sqltask="INSERT INTO tasks ('TName','TDesc') VALUES ('$TaskName','$TaskDesc')";
if ($con->query($sqltask))
header("Location: Tasks.php");
else
header("Location: Add_Task.php");
}
?>
The file DBconnect.php only contains this:
<?php
$con= mysqli_connect("localhost", "root","","first_app")
?>
The problem is that even though the code is similar in both forms only one of them is working. Every time I run the Add_Task.php file it redirects me to the same page (as I instructed it) since it does not add anything to the database.
I also checked the tables just in case it adds something but it does not.
please set your primary_key(id) as auto increment in table tasks. if you not set it might be possible.
and change this line
$sqltask="INSERT INTO tasks ('TName','TDesc') VALUES ('$TaskName','$TaskDesc')";
like this :
$sqltask="INSERT INTO tasks (TName,TDesc) VALUES ($TaskName,$TaskDesc)";
You are mixing OOP style and Procedural Style in your code
You are used Procedural Style in your DBconnect.php file. And You are missing ; in your connection file.
DBconnect.php file should be:
<?php
$con= mysqli_connect("localhost", "root","","first_app");
?>
register_code.php code should be:
<?php
require "DBconnect.php";
$post = $_POST;
if(isset($post)) {
session_start();
$UName = $post['user_name'];
$PW = md5($post['password']);
$FName = $post['first_name'];
$LName = $post['last_name'];
$Email = $post['email'];
$sql = mysqli_query($con,"INSERT INTO users (user_name, password, email, first_name, last_name) VALUES ('$UName','$PW','$Email', '$FName', '$LName')");
if($sql)
header("Location: Registration_successful.php");
else
echo "Please try again to register";
}
include 'Register.php';
Add_Task_code.php file code should be:
<?php
require 'DBconnect.php';
$post=$_POST;
if(isset($post))
{
$TaskName = $post['TName'];
$TaskDesc = $post['TDesc'];
$sqltask="INSERT INTO tasks ('TName','TDesc') VALUES ('$TaskName','$TaskDesc')";
if (mysqli_query($con,$sqltask))
header("Location: Tasks.php");
else
header("Location: Add_Task.php");
}
?>
Try to make the below changes and see what the actual error is.then debug your code.
if($_SERVER['REQUEST_METHOD']=='POST')
{
$TaskName = $post['TName'];
$TaskDesc = $post['TDesc'];
$sqltask="INSERT INTO tasks ('TName','TDesc') VALUES ('$TaskName','$TaskDesc')";
if ($con->query($sqltask))
echo "Successfully Inserted";
else
echo "Error: " . $sqltask. "<br>" . mysqli_error($conn);
}
?>
My PHP form validation is showing blank field upon submit, when form is completely filled.
I keep getting the error code I created On the add.php page:
You did not complete all of the required fields. Press the back button on your browser to try again."
Any suggestions about what I am doing wrong? I am a newbie.
Here is my php code:
//This code runs if the form has been submitted
if (isset($_POST['submit'])) {
//This makes sure they did not leave any fields blank
if (!$_POST['firstname'] | !$_POST['lastname'] | !$_POST['email'] | !$_POST['address'] | !$_POST['phonenumber'] | !$_POST['birthday'] | !$_POST['gender'] | !$_POST['referralsource'] | !$_POST['username'] | !$_POST['password'] | !$_POST['confirmpassword'] ) {
die('You did not complete all of the required fields. Press the back button on your browser to try again.');
}
// checks if the email is in use
if (!get_magic_quotes_gpc()) {
$_POST['email'] = addslashes($_POST['email']);
}
$usercheck = $_POST['email'];
$check = mysql_query("SELECT email FROM dbs WHERE email = '$usercheck'")
or die(mysql_error());
$check2 = mysql_num_rows($check);
//if the name exists it gives an error
if ($check2 != 0) {
die('Sorry, the email '.$_POST['email'].' is already in use.');
}
// checks if the username is in use
if (!get_magic_quotes_gpc()) {
$_POST['username'] = addslashes($_POST['username']);
}
$usercheck = $_POST['username'];
$check = mysql_query("SELECT username FROM db WHERE username = '$usercheck'")
or die(mysql_error());
$check2 = mysql_num_rows($check);
// this makes sure both passwords entered match
if ($_POST['password'] != $_POST['confirmpassword']) {
die('Your passwords did not match. Press the back button on your browser to try again.');
}
// here we encrypt the password and add slashes if needed
$_POST['password'] = md5($_POST['password']);
if (!get_magic_quotes_gpc()) {
$_POST['password'] = addslashes($_POST['password']);
$_POST['username'] = addslashes($_POST['username']);
}
// now we insert it into the database
$insert = "INSERT INTO db (firstname, lastname, email, address1, address2, phonenumber, birthday, gender, referralsource, username, password)
VALUES ('".$_POST['firstname']."', '".$_POST['lastname']."', '".$_POST['email']."', '".$_POST['address']."', '".$_POST['address2']."', '".$_POST['phonenumber']."', '".$_POST['birthday']."', '".$_POST['gender']."', '".$_POST['referralsource']."', '".$_POST['username']."', '".$_POST['password']."')";
$add_member = mysql_query($insert);
?>
<h1>Registered</h1>
<p>Thank you, you have registered - you may now login.</p>
<?php
}
else
{
?>
This is my form
<tr><td>First Name:</td><td>
<input type="text" name="firstname" maxlength="60">
</td></tr>
<tr><td>Last Name:</td><td>
<input type="text" name="lastname" maxlength="60">
</td></tr>
<tr><td>Email:</td><td>
<input type="text" name="email" maxlength="60">
</td></tr>
<tr><td>Address:</td><td>
<input type="text" name="address1" maxlength="60">
</td></tr>
<tr><td>City, State, Zip:</td><td>
<input type="text" name="address2" maxlength="60">
</td></tr>
<tr><td>Phone Number:</td><td>
<input type="text" name="phonenumber" maxlength="13">
</td></tr>
<tr><td>Birthday:</td><td>
<input type="text" name="birthday" maxlength="60">
</td></tr>
<tr><td>Gender:</td><td>
<input type="text" name="gender" maxlength="15">
</td></tr>
<tr><td>Referral Source:</td><td>
<input type="text" name="referralsource" maxlength="60">
</td></tr> <tr><td>Username:</td><td>
<input type="text" name="username" maxlength="20">
</td></tr>
<tr><td>Password:</td><td>
<input type="password" name="password" maxlength="20">
</td></tr>
<tr><td>Confirm Password:</td><td>
<input type="password" name="confirmpassword" maxlength="20">
</td></tr>
<tr><th colspan=2><input type="submit" name="submit"
value="Register"></th></tr> </table>
</form>
<?php
}
?>`
First off, you're not using the OR inside the if condition properly, it should be ||
Instead, you can use isset() if the textbox input is blank. Consider this example:
if (!isset($_POST['firstname'], $_POST['lastname'], $_POST['email'], $_POST['address1'], $_POST['phonenumber'], $_POST['birthday'], $_POST['gender'], $_POST['referralsource'],$_POST['username'], $_POST['password'], $_POST['confirmpassword']) ) {
die('You did not complete all of the required fields. Press the back button on your browser to try again.');
}
Edit: Important Note. Please migrate to mysqli_* functions instead, as you are using a deprecated API.
OK so my register system is correctly inserting into my database the username, password, and e-mail but not any other fields. I first tried putting the values directly into the SQL query and then put them in the form as hidden text fields. The direct values gave an SQL syntax error and the hidden text doesn't insert anything but successfully adds the user, pass, and email. All MYSQL field types are LONGTEXT. Here's the code.
Register.php
<form name="register" method="post" action="register2.php"><br />
Username<br><input name="username" type="text" size="20" /><br /><br />
Password<br><input name="password" type="password" size="20" /><br /><br />
E-mail<br><input name="email" type="text" size="20" /><br /><br />
<input="hidden" id="status" type="text" value=Waiting for a request size="100" />
<input="hidden" id="request" type="text" value="None sent" size="100" />
<input="hidden" id="paid" type="text" value="Please pay for an instant spot" size="100" />
<input="hidden" id="priority" type="text" value="To be determined by your web designer" size="100" />
<input="hidden" id="files" type="text" value="None" size="100" />
<input="hidden" id="filespass" type="text" value=None" size="100" /><div id="captcha2">
<img id="captcha" src="securimage/securimage_show.php" alt="CAPTCHA Image" /><br><br>Please re-write the security code below<br><input type="text" name="captcha_code" size="10" maxlength="6" size="20"/></div>
<br>
<input type="submit" name="submit" value="Register" /><br><br>
<a href='forgot.php'>Forgot</a> your password?<br>
</form>
Register2.php
<?php
include_once 'securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($_POST['captcha_code']) == false) {
// the code was incorrect
// you should handle the error so that the form processor doesn't continue
// or you can use the following code if there is no validation or you do not know how
echo "The security code entered was incorrect.<br /><br />";
echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
exit;
}else{
$con = mysql_connect(secret);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dylanmediagroup", $con);
$username = htmlspecialchars($_POST['username']);
$password = htmlspecialchars($_POST['password']);
$email = htmlspecialchars($_POST['email']);
$status = htmlspecialchars($_POST['status']);
$priority = htmlspecialchars($_POST['priority']);
$paid = htmlspecialchars($_POST['paid']);
$files = htmlspecialchars($_POST['files']);
$filespass = htmlspecialchars($_POST['filespass']);
$checkuser = mysql_query("SELECT * FROM users WHERE username ='$username'");
$checkemail = mysql_query("SELECT * FROM users WHERE email='$password'");
if(mysql_num_rows($checkuser) > 0 ) { //check if there is already an entry for that username
echo "<img src='http://www.myhealthguardian.com/wp-content/uploads/2010/01/sad-face.gif' width='25%' height='21%'><br><br>Account already registered.<br> <a href='forgot.php'>Forgot</a> your password?<br><br>";
} else {
$sql="INSERT INTO `users` (username, password, email, status, priority, paid, files, filespass) VALUES ('$username', '$password', '$email', '$status', '$priority', '$paid', '$files', '$filespass')";
}
if (!mysql_query($sql,$con))
{
}else{
echo "<img src='http://3.bp.blogspot.com/-vpsc13PCfc0/TaLCGaq2SjI/AAAAAAAACTA/hw2MDzTk6mg/s1600/smiley-face.jpg' height='21%' width='25%'><br><br>Your registration was successful, please <a href='login.php'>login</a> to continue.";
}
}
mysql_close($con)
?>
You're using id instead of name for your hidden inputs.
And please use this syntax:
<input type="hidden" name="name" value="value" />
Also one of your values seem to break the string since it has quotation marks in it.