PHP - Checking for Duplicate Entry - php

I have a simple entry form which includes an email address. I want to check for a duplicate (which I can do) but what I'm struggling with is how to get the entry form to indicate it is a duplicate "Please Try Again".
The Entry Form code is as follows:
<form action="mailer2.php" method="POST">
<div>
<p class="auto-style1" style="width: 408px">Newsletter Sign-Up Form</p>
<p>First Name</p>
<input name="firstname" type="text"> <br> </div>
<div>
<p>Last Name</p>
<input name="lastname" type="text">
<br>
</div>
<p>E-Mail</p>
<input name="email" type="text">
<br>
</div>
<div>
<p>What are your interests"</p><br>
<input type="checkbox" name="activity[]" value="run">I enjoy running<br>
<input type="checkbox" name="activity[]" value="bike">
I enjoy mountain biking<br>
<input type="checkbox" name="activity[]" value="hike">I enjoy hiking<br>
</div>
<div>
<input name="submit" type="submit" value="Send!"> </div>
</form>
The PHP code: This is where I am stuck...how do I get back to my form and note below the email address it is a duplicate
<?php
$hostname = "hostname";
$username = "Username";
$password = "password";
$dbname = "Tablename";
$TableName = "MemberInfo";
// Check connections
mysql_connect($hostname, $username, $password) or die("cannot connect");
mysql_select_db("$dbname")or die("cannot select DB");
// Get values from form
$fname=$_POST['firstname'];
$lname=$_POST['lastname'];
$email=$_POST['email'];
$FullName = $fname . " " . $lname;
$activity=$_POST['activity'];
$run = 0;
$bike = 0;
$hike = 0;
//Check for Duplicate Email
$result = mysql_query("SELECT * FROM MemberInfo WHERE Email='$email'");
$DupCheck = mysql_num_rows($result);
if ($DupCheck) {
echo "Email already exists ... please try again.";
//header('Location: NewsletterSignUp.html');
exit;
//trigger_error('Email Already Exists.', E_USER_WARNING);
}
if (isset($_POST['activity'])) {
$activity = $_POST['activity'];
foreach($activity as $key => $value) {
//echo $key. ' = ' . $value . '<br>';
if ($value == 'run') {
$run = 1;
}
if ($value == 'bike') {
$bike = 1;
}
if ($value == 'hike') {
$hike = 1;
}
}
} else {
echo 'Nothing';
}
// Insert data into mysql
$sql="INSERT INTO $TableName (FirstName, LastName, FullName,
Email, Run, Bike, Hike) VALUES('$fname', '$lname',
'$FullName', '$email', '$run',
'$bike', '$hike')";
$result=mysql_query($sql);
// if successful insert data into database, displays message "Successful".
if($result){
header('Location: Confirmation.html');
}
else {
die('Invalid query: ' . mysql_error());
}
if(isset($_POST['submit'])) {
// Send email
$to = "someone#example.com";
$subject = "Newsletter Sign-Up";
// data the visitor provided
$fname_field = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);
$lname_field = filter_var($_POST['lastname'], FILTER_SANITIZE_STRING);
$email_field = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
foreach($_POST['activity'] as $value) {
$activity_field .= "Checked: $value\n";
}
//constructing the message
$body = " From: $fname_field $lname_field\n\n
E-Mail: $email_field\n\n$activity_field";
// ...and away we go!
mail($to, $subject, $body);
} else {
// handle the error somehow
}
?>
<?php
// close connection
mysql_close();
?>
(edit - show form html)

The easiest way would be making email field as UNIQUE with index, then it will be no possible to add 2 same e-mail fields. The other way is to make select with this mail and check if there is record with this field.
Also don't use mysql_* functions they are old and will be removed in future.
here is more about unique index http://dev.mysql.com/doc/refman/5.0/en/create-index.html
In my personal experience I like to put a lot of things into database, if there is something that can be checked via database, why don't use it?
Make change into your Db
ALTER TABLE $TABLE
ADD UNIQUE INDEX Email(Email);
or
CREATE UNIQUE INDEX unique_email
ON $TABLE (Email)
adding new row where there is already email will return error or if you use pdo it will throw exception. Something like:
ERROR 1062 (23000): Duplicate entry 'xxx' for key 1.

Related

How to update user input of a form when i am using header that links to other file?

I am writing a form using php and mysql. The main goal is to make the form
(1) detect missing field.
(2) update user input after successful submit and
(3) most importantly to avoid re-submission on reload/refresh.
I am able to manage the first and the third one but doesn't have any idea on the second one.
Here's my code (able to achieve first and third)
form1.php
<!DOCTYPE html>
<html>
<head></head>
<body>
<?php
$name = "";
$class = "";
$school = "";
if(isset($_POST["submit"])){
$name = $_POST["name"];
$class = $_POST["class"];
$school = $_POST["school"];
$output = false;
if(empty($_POST["name"]) || empty($_POST["class"]) || empty($_POST["school"])){
echo 'field cannot be empty';
$output_form = true;
}
if(!empty($_POST["name"]) && !empty($_POST["class"]) && !empty($_POST["school"])){
$hostname = "localhost";
$admin = "root";
$password = "";
$database = "testdatabase";
$dbc = mysqli_connect($hostname, $admin, $password, $database) or die("database connection error");
$insert_query = "INSERT INTO `sorty` (`name`, `class`, `school`) VALUES ('$name', '$class', '$school')";
$insert_result = mysqli_query($dbc, $insert_query) or die("error");
if($insert_result == 1)
echo "data inserted";
else
echo "insert query failed";
mysqli_close($dbc);
header('Location: form2.php');
}
}
else
$output = true;
if($output){
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Name: <input type="text" name="name" value="<?php echo $name?>"/><br/>
Class: <input type="text" name="class" value="<?php echo $class?>"/><br/>
School: <input type="text" name="school" value="<?php echo $school?>"/><br/>
<input type="submit" value="submit" name="submit"/>
</form>
<?php
}
?>
</body>
</html>
My second file form2.php(succesful page after form submission)
<body>
Name: /*user input here*/<br/>
Class: /*user input here*/<br/>
School: /*user input here*/<br/>
As I can't access the variable $name, $class, $school of form.php I am having problem updating the user input data. So is there anyway to access the variable across file or is it not possible to do in this way.
user_name you may check this out. and read the code. i hope you will get the answer. You may add session for showing the message that the specified operation is done. thank you :)

MySQL database not selected. where did I miss it?

After searching through related questions, I still couldn't get this issue resolved. A "registration successful" page is supposed to pop up after a form is submitted but instead, "No database selected" message appears. where did I miss it. here are the codes.
connect.php
<?php
//connect.php
$server = 'localhost';
$username = 'root';
$password = '';
$database = 'esiro';
$connection = mysqli_connect($server, $username, $password, $database);
mysqli_set_charset($connection,"utf8");
?>
signup.php
<?php
//signup.php
include 'connect.php';
include 'header.php';
echo '<h3>Sign up</h3>';
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 role="form" method="post" action="" class="cover_form">
<div class="form-group">
<label class="labelfield" for="username">User Name:</label><br>
<input class="inputfield" type="text" name="user_name" class="form-control"/><br>
<label class="labelfield" for="pwd">Password:</label><br>
<input class="inputfield" type="password" class="form-control" id="pwd" name="user_pass"><br>
<label class="labelfield" for="pwd"> Confirm Password:</label><br>
<input class="inputfield" type="password" name="user_pass_check" class="form-control" id="pwd"><br>
<label class="labelfield" for="email">Email Address:</label><br>
<input class="inputfield"type="email" class="form-control" id="email" name="user_email">
</div><br>
<input type="submit" class="btn btn-default" value="Complete Registration"/><br>
</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['user_name']))
{
//the user name exists
if(!ctype_alnum($_POST['user_name']))
{
$errors[] = 'The username can only contain letters and digits.';
}
if(strlen($_POST['user_name']) > 30)
{
$errors[] = 'The username cannot be longer than 30 characters.';
}
}
else
{
$errors[] = 'The username field must not be empty.';
}
if(isset($_POST['user_pass']))
{
if($_POST['user_pass'] != $_POST['user_pass_check'])
{
$errors[] = 'The two passwords did not match.';
}
}
else
{
$errors[] = 'The password field cannot be empty.';
}
if(!empty($errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/
{
echo 'Uh-oh.. a couple of fields are not filled in correctly...';
echo '<ul>';
foreach($errors as $key => $value) /* walk through the array so all the errors get displayed */
{
echo '<li>' . $value . '</li>'; /* this generates a nice error list */
}
echo '</ul>';
}
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
$sql = "INSERT INTO
users(user_name, user_pass, user_email ,user_date, user_level)
VALUES('" . mysql_real_escape_string($_POST['user_name']) . "',
'" . sha1($_POST['user_pass']) . "',
'" . mysql_real_escape_string($_POST['user_email']) . "',
NOW(),
0)";
$result = mysql_query($sql);
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while registering. Please try again later.';
echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
echo 'Successfully registered. You can now sign in and start posting! :-)';
}
}
}
include 'footer.php';
?>
You should Change the script
$result = mysql_query($sql);
Instead of use this
---------------------
$result = mysqli_query($connection,$sql);
And also remove echo mysql_error();
and use this echo mysql_error($connection);
Add this also in instead of mysql_real_escape_string
$sql = "INSERT INTO
users(user_name, user_pass, user_email ,user_date, user_level)
VALUES('" . mysqli_real_escape_string($connection,$_POST['user_name']) . "',
'" . sha1($_POST['user_pass']) . "',
'" . mysqli_real_escape_string($connection,$_POST['user_email']) . "',
NOW(),
0)";

I am attempting to make a login using phpmyadmin, but, when I click submit, it inserts blank entries into the database

My class is attempting to make our own game.. But, we can't get the submit page to send to the database in PhpMyAdmin. When you click submit, it sends blank entries to the database, like if you hadn't filled in any of the blanks. Can someone help with this problem. Thanks!!
My index.php page.
<html>
<head>
<meta charset="UTF-8">
<title> Register New Account </title>
<link rel="stylesheet" type="text/css" href="td.css">
</head>
<body>
<?php
/* $count=$count+1;
echo " count " . $count; */
if($_POST['submit_id'] == 1)
{
/* echo "testing"; */
if($_POST['Username'] == NULL)
{
$message = 'Please enter your Username.';
}
if($_POST['Email'] == NULL)
{
$message = 'Please enter your Email.';
}
if($_POST['Confirm'] == NULL)
{
$message = 'Please re-enter your Email.';
}
if($_POST['Password'] == NULL)
{
$message = 'Please enter your Password.';
}
if($_POST['Email'] != $_POST['Confirm'])
{
$message = 'Your emails did not match, Please enter your emails again.';
}
}
if( $message == NULL )
{
// if there is no error, test to see if there is already an account by the player_name
$MySQLlink = new mysqli("localhost", "root", "******", "Tower_Defense");
// check connection - take out later
if ( !$MySQLlink )
{
printf( "Could not connect to MySQL server : %s", mysqli_connect_error() );
exit();
}
else
{
printf( "Connected to the MySQL server" );
echo "<br>";
}
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( email = 'email' ) " );
if($row = mysqli_fetch_array($result))
{
$message = "There is an account with that email address already. Please choose another email account";
}
mysqli_free_result($result);
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( Username = '$Username' ) " );
if( $row = mysqli_fetch_array($result) && $message == NULL )
{
$message = "There is an account by that player name already. Please choose another Login name";
mysqli_free_result($result);
}
else
{
//echo "next date <br>";
// create account
$Username = ($_POST['Username']);
$Password = ($_POST['Password']);
$Email = ($_POST['Email']);
$email = ($_POST['email']);
//echo "Next one<br>";
$TableList = " `Username`, `Password`, `Email`, `Confirm` ";
$Values = " '$Username', '$Password', '$Email', '$Confirm' ";
if($message != NULL)
{
echo "$message";
}
?>
<div id="container" >
<div id="header">
<h1 id="h1">Besco's Biscuits</h1>
About
Instructions
The Creation Of The Game
Contact Us
</div>
<br /> <br /> <br />
<table align = "center">
<tr>
<td>
Welcome to <b> Besco's Biscuits </b>. Please fill out the following <br />
areas and we will begin your adventure soon. :)
</td>
</tr>
</table>
<br /> <br /> <br /> <br /> <br />
<table align = "center">
<tr>
<td>
<form action = "<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"> <br />
Username: <input type="text" name="Username" id= "Username"> <br />
Email: <input type = "text" name = "Email" id= "Email"> <br />
Confirm: <input type = "text" name = "Confirm" id= "Confirm"> <br />
Password: <input type = "password" name = "Password" id = "Password"> <br />
<input type = "submit" value = "Register" id="submit_id" value = "1">
<input type = "reset" name="Reset" value="Check if Available!" class = "account">
</form>
</td>
</tr>
</table>
</body>
</html>
My insert.php page
<html>
<body>
<?php
$Username = $_POST['name'];
$con=mysqli_connect("localhost", "root", "******", "Tower_Defense");
//Check Connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Users (Username, Email, Confirm, Password)
VALUES
('$_POST[Username]','$_POST[Email]',' $_POST[Confirm]',' $_POST[Password]')";
if (!mysqli_query($con,$sql))
{
die ('Error: ' . mysqli_error($con));
}
else
{
echo "1 record added";
echo $_POST[Username];
//echo "Where is Username?";
echo $_POST[Email];
//echo "Where is Email?";
echo $_POST[Confirm];
//echo "Where is Confirm";
echo $_POST[Password];
//echo "Where is Password";
}
mysqli_close($con);
?>
</body>
UPDATE:
I added in the changes that someone had suggested in moving the checks to insert.php and now the email and confirm email check does not work. Can anyone help?
index.php
<html>
<body>
<div id="container" >
<div id="header">
<h1 id="h1">Besco's Biscuits</h1>
About
Instructions
The Creation Of The Game
Contact Us
</div>
<br /> <br /> <br />
<table align = "center">
<tr>
<td>
Welcome to <b> Besco's Biscuits </b>. Please fill out the following <br />
areas and we will begin your adventure soon. :)
</td>
</tr>
</table>
<br /> <br /> <br /> <br /> <br />
<table align = "center">
<tr>
<td>
<form action = "insert.php" method = "post"> <br />
Username: <input type="text" name="Username" id= "Username" required = "1"> <br />
Email: <input type = "text" name = "Email" id= "Email" required = "1"> <br />
Confirm: <input type = "text" name = "Confirm" id= "Confirm" required = "1"> <br />
Password: <input type = "password" name = "Password" id = "Password" required = "1"> <br />
<input type = "submit" value = "Register" id="submit_id" value = "1">
<input type = "reset" name="Reset" value="Reset Page" class = "account">
</form>
</td>
</tr>
</table>
</body>
</html>
insert.php
<html>
<body>
<?php
if($_POST['submit_id'] == 1)
{
echo "testing";
if($_POST['Email'] != $_POST['Confirm'])
{
$message = 'Your emails did not match, Please enter your emails again.';
}
}
if( $message == NULL )
{
// if there is no error, test to see if there is already an account by the player_name
$MySQLlink = new mysqli("localhost", "root", "abc123", "tower_defense");
// check connection - take out later
if ( !$MySQLlink )
{
printf( "Could not connect to MySQL server : %s", mysqli_connect_error() );
exit();
}
else
{
printf( "Connected to the MySQL server" );
echo "<br>";
}
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( email = 'email' ) " );
if($row = mysqli_fetch_array($result))
{
$message = "There is an account with that email address already. Please choose another email account";
}
mysqli_free_result($result);
$result = mysqli_query( $MySQLlink, "SELECT * FROM Users WHERE ( Username = '$Username' ) " );
if( $row = mysqli_fetch_array($result) && $message == NULL )
{
$message = "There is an account by that player name already. Please choose another Login name";
mysqli_free_result($result);
}
else
{
//echo "next date <br>";
// create account
$Username = ($_POST['Username']);
$Password = ($_POST['Password']);
$Email = ($_POST['Email']);
$email = ($_POST['email']);
//echo "Next one<br>";
}
}
if($message != NULL)
{
echo "$message";
}
$con=mysqli_connect("localhost", "root", "abc123", "tower_defense");
//Check Connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Users (Username, Email, Confirm, Password)
VALUES
('$_POST[Username]','$_POST[Email]',' $_POST[Confirm]',' $_POST[Password]')";
if (!mysqli_query($con,$sql))
{
die ('Error: ' . mysqli_error($con));
}
else
{
echo "1 record added";
echo $_POST[Username];
//echo "Where is Username?";
echo $_POST[Email];
//echo "Where is Email?";
echo $_POST[Confirm];
//echo "Where is Confirm";
echo $_POST[Password];
//echo "Where is Password";
}
mysqli_close($con);
?>
</body>
</html>
I see two main problems here -
First, the action of your form points to itself. That means that the $_POST array submits to index.php, and your insert.php page has no access to that information. Index.php runs through the validation checks, and if everything checks out, it assigns the $_POST values to variables and quits. That's where the data dies. There is no method for getting the information over to the file insert.php. So if you manually open the file insert.php in a browser, the $_POST array will be empty, and it will simply insert blanks.
There are several ways to resolve this. The simplest, most expeditious way would be the single page solution - move the insert.php code into the index.php file inside that last else block.
else {
//echo "next date <br>";
// create account
$Username = $_POST['name'];
//etc.. code to insert data from insert.php
Another solution would be to move all the validation code to insert.php, display any form errors on that page, and make the user go back a page if validation fails. In that case, you would change the action of the form to insert.php:
<form action="insert.php" method="post">
This approach is less user-friendly, and not an ideal solution. Really a better practice is to use Javascript for form validation and PHP for form processing. That may be outside the scope of your class...
Second, this code is wide open to SQL injection. Instead of putting variables directly into your SQL statements, you need to use parameterized queries. Take a look at this SO question about how to parameterize queries with mysqli.
The mistakes that I found:
First things first your code submits the values received from the form to index.php itself so there is no question of values getting insert at the first place because the insert query is not run.
In index.php check the query to SELECT email and username. The variables do not have any value when the query is run because the values get transferred couple of lines AFTER the queries (at the lines where you have $email = $_POST['Email']). Moreover you have missed the $ sign in the query related to email.
Coming to insert.php you have missed quotes in the global variable $_POST[] in the insert query viz. $_POST['email'].
Check for these errors and let me know if it works.

I am trying to get some form data with php and put it in my mysql db, not sure what's wrong

I am trying to teach my self how to code websites and I need to get some info from a form and put it in my mysql db, and from what I have gathered the best way to do what I want is to use php. When I hit the submit button, the script in my index.php executes but nothing gets put in the db. the script links to another script that is out side my web root. I needed to put it out there because it contains passwords (is there a better way to do this?) this may be part of my problem. Below are the relevant pieces of code:
<?php
$con=mysqli_connect("192.168.1.125","root","pass","site");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO users (Email)
VALUES
('$_POST[email]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
and
<?php
// define variables and set to empty values
$emailErr = "";
$email = $password = "";
$file = basename(urldecode($_GET['insert.php']));
$fileDir = '/var/insert.php';
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["email"]))
{$emailErr = "email is required";}
else
{$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (file_exists($fileDir . $file))
{
// Note: You should probably do some more checks
// on the filetype, size, etc.
$contents = file_get_contents($fileDir . $file);
// Note: You should probably implement some kind
// of check on filetype
header('Content-type: php');
echo $contents;
}
?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input id="email" placeholder=" email" type="email" name="email" maxlength="50">
<input id="pass" placeholder=" Password" type="password" name="pass" maxlength="25">
<button id="submit">SUBMIT</button></form>
</div>
</div><div id="date" align="center"><img src="192.168.1.125/date.png"></div>
<?php
echo "<h2>Your Input:</h2>";
echo "$email";
echo "$emailErr";
?>
change the line,
$sql="INSERT INTO users (Email) VALUES ('$_POST[email]')";
with
$sql="INSERT INTO users (Email) VALUES ('".$_POST['email']."')";
$email = mysqli_real_escape_string($con, $_POST['email']);
$sql="INSERT INTO users (Email)
VALUES
('$email')";

PHP SQL registration form

I am attempting a registration form that saves the data into a sql db. I'm not doing form validation just yet as what is most troubling me is getting this stuff onto sql. I'd appreciate any advice!!
I have a form.php file that should be doing the hard work. When I submit my form, at this point, I get a blank screen and nothing loads into the database.
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$password = $_POST['password'];
$email = $_POST['email'];
$cell = $_POST['cell'];
$experience = $_POST['experience'];
$ip = $_POST['ip'];
$password = md5($_POST['password']);
$connection = msql_connect(localhost, USERNAME, PASSWORD);
$db = mysql_select_db(registration,$connection);
mysql_query("INSERT INTO userTable (fname,lname,password,email,cell,experience,ip) VALUES ('$fname', '$lname', '$password', '$email', '$cell', '$experience', '$ip')")
or die (mysql_error());
echo "Thank you for your registration";
?>
And I have an html file that contains this:
<form method = "post" action = "form.php">
<h2>User Information</h2>
<div><label>First Name:</label>
<input type = "text" name = "fname"></div>
<div><label>Last Name:</label>
<input type = "text" name = "lname"></div>
<div><label>Password:</label>
<input type = "password" name = "password"></div>
<div><label>Email:</label>
<input type="text" name="email"></div>
<div><label>Cellphone:</label>
<input type="text" name="cell"></div>
<input type="hidden" name="ip" value='<?php echo $IP ?>'/>
<h2>What Is Your Experience Mountain Biking?</h2>
<p><input type="radio" name="experience" value="n00b"
checked>n00b
<input type="radio" name="experience" value="intermediate">Intermediate
<input type="radio" name="experience" value="extreme">Extreme
</p>
<p><input type="submit" name="submit" value="Register"></p>
</form>
Finally, I have a sql database (I'm running xampp locally) called "registration"
The table I've created is called "userTable" and it contains 8 fields including ID (auto incrementing) and the 7 other values I've included up top. Any idea what the heck I'm doing wrong?
What is the problem?
1) The problem is that it does INSERT query each time you load this page - mean each time it inserts empty values. Why?
Simply because there's no condition that checks if all fields has been posted, so instead of:
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$password = $_POST['password'];
$email = $_POST['email'];
$cell = $_POST['cell'];
$experience = $_POST['experience'];
$ip = $_POST['ip'];
You should check if $_POST super-global has some keys.
So before doing any queries - first of all check if $_POST isn't empty
<?php
//This means that user did submit the form
if ( !empty($_POST) ){
//all your stuff goes here
}
?>
<html>
.....
</html>
2) Are you sure you are in control of your code? Apparently not.
You MUST check if some function returned TRUE and then make following actions relying on it's one.
For example, are you sure that mysql_query("your sql query") was succeed at?
3) Enable error_reporting to E_ALL, so just put error_reporting(E_ALL) at the top of your page, like this:
<?php
error_reporting(E_ALL);
So that you can always debug your script "on fly"
4) You are doing everything to make this code hard to maintain, Why?
Look at this:
<?php
//Debug mode:
error_reporting(E_ALL);
//Sure you want to show some error if smth went wrong:
$errors = array();
/**
*
* #return TRUE if connection established
* FALSE on error
*/
function connect(){
$connection = mysql_connect(localhost, USERNAME, PASSWORD);
$db = mysql_select_db(registration,$connection);
if (!$connection || !$db ){
return false;
} else {
return true;
}
}
//So this code will run if user did submit the form:
if (!empty($_POST)){
//Connect sql server:
if ( !connect() ){
$errors[] = "Can't establish link to MySQL server";
}
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$password = $_POST['password'];
$email = $_POST['email'];
$cell = $_POST['cell'];
$experience = $_POST['experience'];
//Why post ip? not smth like $_SERVER['REMOTE_ADDR']...
$ip = $_POST['ip'];
$password = md5($_POST['password']);
//No error at this point - means that it successfully connected to SQL server:
if ( empty($errors) ){
//let's prevent sql injection:
$fname = mysql_real_escape_string($fname);
//Please do this for all of them..
}
//Now we should try to INSERT the vals:
$query = "INSERT INTO `userTable` (`fname`,`lname`,`password`,`email`,`cell`,`experience`,`ip`) VALUES ('$fname', '$lname', '$password', '$email', '$cell', '$experience', '$ip')";
//So try it:
if ( !mysql_query($query) ){
//
//die (mysql_error());
$errors[] = "Can't insert the vals";
} else {
//Or on success:
print ("Thank you for your registration");
//or you can do redirect to some page, like this:
//header('location: /thanks.php');
}
}
?>
<form method="post">
<h2>User Information</h2>
<div><label>First Name:</label>
<input type = "text" name = "fname"></div>
<div><label>Last Name:</label>
<input type = "text" name = "lname"></div>
<div><label>Password:</label>
<input type = "password" name = "password"></div>
<div><label>Email:</label>
<input type="text" name="email"></div>
<div><label>Cellphone:</label>
<input type="text" name="cell"></div>
<input type="hidden" name="ip" value='<?php echo $IP ?>'/>
<h2>What Is Your Experience Mountain Biking?</h2>
<p><input type="radio" name="experience" value="n00b"
checked>n00b
<input type="radio" name="experience" value="intermediate">Intermediate
<input type="radio" name="experience" value="extreme">Extreme
</p>
<?php if ( !empty($errors) ) : ?>
<?php foreach($errors as $error): ?>
<p><b><?php echo $error; ?></b></p>
<?php endforeach; ?>
<?php endif; ?>
<p><input type="submit" name="submit" value="Register"></p>
</form>
Solved my own problem
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$password = $_POST['password'];
$email = $_POST['email'];
$cell = $_POST['cell'];
$experience = $_POST['experience'];
$ip = $_POST['ip'];
$fname = mysql_real_escape_string($fname);
$lname = mysql_real_escape_string($lname);
$email = mysql_real_escape_string($email);
$password = md5($_POST['password']);
$servername="localhost";
$username="user";
$conn= mysql_connect($servername,$username, password)or die(mysql_error());
mysql_select_db("registration",$conn);
$sql="insert into userTable (fname,lname,password,email,cell,experience,ip) VALUES ('$fname', '$lname', '$password', '$email', '$cell', '$experience', '$ip')";
$result=mysql_query($sql,$conn) or die(mysql_error());
print "<h1>you have registered sucessfully</h1>";
echo "Thank you for your registration to the ";
mysql_close($connection);
?>

Categories