having problems making a program with PHP - php

I created two forms, one is registration form the other is picking the dates the user will come and leave. I called the user's username in the 2nd page.. and although i receive it, i get a message "error" and nothing gets updated on my database. Here is my 2nd page file.. What am i doing wrong?
<?php
session_start();
$EntryError=$ExitError="";
if (isset($_POST['submit'])){
$entrydate = $exitdate = "";
$errorOccured = false;
if (isset($_POST['tsmdate'])){
$entrydate = trim($_POST['tsmdate']);
if (strlen($entrydate) == 0){
$EntryError = "date is missing";
$errorOccured = true;
}
}
else{
$EntryError = "date is missing";
}
// checking for last name
if (isset($_POST['tsmexit'])){
$exitdate = trim($_POST['tsmexit']);
if (strlen($exitdate) == 0){
$ExitError = "First Name is missing";
$errorOccured = true;
}
}
else{
$ExitError = "last Name is missing";
}
$ids=$_SESSION['tsmUserName'];
var_dump($_SESSION);
if(!$errorOccured){
require_once("connection.php");
$my_query="INSERT INTO timing (No, Entry Date and Time, Exit Date and Time, user_id) VALUES (NULL,'$EntryError','$exitdate','$ids')";
$result=mysqli_query($connection,$my_query);
if($result)
{
echo 'thank you';
}
else
{
echo 'error';
}
mysqli_close($connection);
}
}
?>
<html>
<head>
</head>
<body>
<form name="dates" id="dates" method="POST" action="">
<table cellpadding="5" border="0" width="100%">
<tr>
<td colspan="3" align="center">
<h1> select dates </h1>
</td>
</tr>
<tr>
<td width="30%" align="right">
<label for="tsmdate">Entry date and time</label>
</td>
<td align="left">
<input type="text" name="tsmdate" id="tsmdate" required="required">
</td>
</tr>
<tr>
<td width="30%" align="right">
<label for="tsmexit">Exit date and time</label>
</td>
<td align="left">
<input type="text" name="tsmexit" id="tsmexit" required="required">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="submit" value="dates">
</td>
</tr>
</table>
</form>
</body>
</html>

Change INSERT query to this
$my_query="INSERT INTO timing (`No`, `Entry Date and Time`, `Exit Date and Time`, `user_id`) VALUES (NULL,'$EntryError','$exitdate','$ids')";
Make sure if any database field name has space in name, then it should be within ` (back tic)

Your insert query isn't a valid query because of the spaces in your column names, I suggest your change the spaces into '_' characters so you won't walk into more trouble. If you like to keep the spaces you have to escape the column names with the "`" character.
Example
$query="INSERT INTO timing (`No`, `Entry Date and Time`, `Exit Date and Time`, `user_id`) VALUES (NULL, '$EntryError', '$exitdate', '$ids')";
Your form is very vulnerable to SQL injection, to prevent this you have to escape your variables with the mysqli::real_escape_string function.
Example
$EntryError = mysqli_real_escape_string($connection, $EntryError);
$exitdate = mysqli_real_escape_string($connection, $exitdate);
$query="INSERT INTO timing (`No`, `Entry Date and Time`, `Exit Date and Time`, `user_id`) VALUES (NULL, '$EntryError', '$exitdate', '$ids')";

Related

Php/MySQL: time isn't matching properly with current time

I created a program where u type in the date and time and then on clicking submit, it tells you whether the typed in date and time are same as the current date and time.. the problem i am having with the time part is that no matter what time i put in, it says "same time" idk why. The date one is working fine but the time one isn't.
<?php
session_start();
$EntryError=$EntryTimeError="";
if (isset($_POST['submit'])){
$entrydate = $EntryTime = "";
$errorOccured = false;
if (isset($_POST['tsmdate'])){
$entrydate = trim($_POST['tsmdate']);
if (strlen($entrydate) == 0){
$EntryError = "date is missing";
$errorOccured = true;
}
else{
$presentDate=date('Y-m-d');
if(strtotime($entrydate) == strtotime($presentDate))
{
echo "same date";
}
else{
echo "different date";
}
}
}
else{
$EntryError = "date is missing";
}
if (isset($_POST['tsmTime'])){
$EntryTime = trim($_POST['tsmTime']);
if (strlen($EntryTime) == 0){
$EntryTimeError = "time is missing";
$errorOccured = true;
}
else{
$EntryTimeError = "time is missing";
$presentTime= date('h:i A', strtotime($EntryTime));
if(strtotime($EntryTime) == strtotime($presentTime))
{
echo "same time";
}
else{
echo "different time";
}
}
}
else{
$EntrytError = "time is missing";
}
}
?>
<html>
<head>
</head>
<body>
<form name="dates" id="dates" method="POST" action="">
<table cellpadding="5" border="0" width="100%">
<tr>
<td colspan="3" align="center">
<h1> select dates </h1>
</td>
</tr>
<tr>
<td width="30%" align="right">
<label for="tsmdate">Entry date </label>
</td>
<td align="left">
<input type="date" name="tsmdate" id="tsmdate" required="required">
</td>
</tr>
<tr>
<td width="30%" align="right">
<label for="tsmTime">Entry time</label>
</td>
<td align="left">
<input type="time" name="tsmTime" id="tsmTime" required="required">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" name="submit" value="dates">
</td>
</tr>
</table>
</form>
</body>
</html>
The $presentTime is always the same as the $EntryTime. This is because you use the entry time in the date function.
Change
$presentTime= date('h:i A', strtotime($EntryTime));
to
$presentTime= date('h:i A');

inserting values in to database only once

<?php if(isset($_POST['submit']))
{
$tadd=$_POST["tadd"]; //getting values
$pname=$_POST["pname"];
$date=$_POST["date"];
$result=mysql_query("insert into pannel(tadd,pname,date)values('$tadd','$pname','$date')");
echo "<script type='text/javascript'>
alert('Quotation Generated Successfully!')
</script>";
} ?>
<center>
<h1>Title</h1>
</center>
<form name="form" method="post" action="" onSubmit="submit;">
<center><table border="0" cellspacing="0" style="width:350px">
<tr> <td><b>To Address</td> <td><textarea name="tadd" rows="5"
cols="30"></textarea></td></tr>
<tr> <td><b>Project Name</td> <td><input type="text" name="pname" required></td></tr>
<tr> <td><b>Date</td> <td><input type="text" name="date"
id="datepicker" required></td></tr>
<tr> <td colspan="2" align="center"><input type="submit" name="submit"
value="submit"/></td> </tr></center> </table> </form>
I have one record in my database with
id tadd pname date
1 hello vvv 22/10/2014
if i insert values into database again it should data already inserted
please help me regarding this issue
You can achieve this using mysql_num_rows() which is one way to do this, which I believe the goal is to avoid duplicates.
Sidenote: You can also set your column(s) as UNIQUE to avoid duplicates.
N.B.: I used the pname column as an example. It's up to you to check which one will always be unique in regards to a username for instance.
$query = "SELECT * FROM pannel where pname = '".$pname."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0){
echo "Already exists.";
}
else{
mysql_query("insert into pannel (tadd, pname,date) values ('$tadd','$pname','$date')");
}
Do sanitize your data:
$tadd = mysql_real_escape_string($_POST["tadd"]);
and do the same for the others.
Even better, use mysqli with prepared statements, or PDO with prepared statements.
They're much safer, because your present code is open to SQL injection.
Footnotes:
You should get rid of onSubmit="submit;" in your form. As outlined in comments, it's not going to do anything.
Edit:
<?php
// assuming DB connection has been made.
if(isset($_POST['submit'])) {
$tadd= mysql_real_escape_string($_POST["tadd"]);
$pname= mysql_real_escape_string($_POST["pname"]);
$date= mysql_real_escape_string($_POST["date"]);
$query = "SELECT * FROM pannel where pname = '".$pname."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0){
echo "Already exists.";
exit;
}
else{
mysql_query("insert into pannel (tadd, pname,date) values ('$tadd','$pname','$date')");
echo "<script type='text/javascript'>alert('Quotation Generated Successfully!')</script>";
}
} // brace for if(isset($_POST['submit']))
?>
<!DOCTYPE html>
<head></head>
<body>
<center><h1>Title</h1></center>
<form method="post" action="">
<div align="center">
<center>
<table border="0" cellspacing="0" style="width:350px">
<tr> <td><b>To Address</td> <td><textarea name="tadd" rows="5" cols="30"></textarea></td></tr>
<tr> <td><b>Project Name</td> <td><input type="text" name="pname" required></td></tr>
<tr> <td><b>Date</td> <td><input type="text" name="date" id="datepicker" required></td></tr>
<tr> <td colspan="2" align="center">
<input type="submit" name="submit" value="submit"/>
</td> </tr>
</table>
</center>
</div>
</form>
</body>
</html>

php validation code format

Okay I have this MySQL database form and am trying to add validation to it. After 2 days of fighting with it, I thought I would get some advice. Would like that the selected item from dropdown and Firstname, Phone, Email, are all required. Then I want to verify that the data in the Firstname, Lastname, Phone (doesn't have to be any special format), Email and Comments are all acceptable formats before putting in database. Here is what I have so far:
<?php
include('inc_header.php');
if(isset($_POST['add']))
{
require('dbcon.php');
if(! get_magic_quotes_gpc() )
{
$Id = addslashes ($_POST['Id']);
$List = addslashes ($_POST['List']);
$Firstname = addslashes ($_POST['Firstname']);
$Lastname = addslashes ($_POST['Lastname']);
$Phone = addslashes ($_POST['Phone']);
$Email= addslashes ($_POST['Email']);
$Calltime = addslashes ($_POST['Calltime']);
$Comment = addslashes ($_POST['Comment']);
}
else
{
$Id = $_POST['Id'];
$Date = $_POST['Date'];
$List = $_POST['List'];
$Firstname = $_POST['Firstname'];
$Lastname = $_POST['Lastname'];
$Phone = $_POST['Phone'];
$Email = $_POST['Email'];
$Calltime = $_POST['Calltime'];
$Comment = $_POST['Comment'];
}
$error = '';
//put chosen function here
function validate_Firstname($input, $pattern = "/([A-Za-z0-9])")
{
return !preg_match($pattern, $input);
}
function validate_Phone($input, $pattern = "/([A-Za-z0-9])")
{
return !preg_match($pattern, $input);
}
function isValidEmail( $Email ){
return filter_var( $Email, FILTER_VALIDATE_EMAIL );
}
//get values and validate each one as required
$List = mysql_real_escape_string($_POST['List']);
if(!$List){ $error .= "Please choose one<br />"; }
$Firstname = mysql_real_escape_string($_POST['Firstname']);
if(!$Firstname){ $error .= "First name is required<br />"; }
//get values and validate each one as required
$Lastname = mysql_real_escape_string($_POST['Lastname']);
if(!$Lastname){ $error .= "Last name is required<br />"; }
//repeat for each field
$Email = mysql_real_escape_string($_POST['Email']);
if(!isValidEmail($Email)){ $error .= "The email entered is invalid<br />"; }
//and so on...
if(!$error){
//add insert into database code here
$sql = "INSERT INTO contacts ".
"(`Id`,`Date`,`List`,`Firstname`,`Lastname`,`Phone`,`Email`,`Calltime`,`Comment`)".
"VALUES'$Id,','$Date','$List','$Firstname','$Lastname','$Phone','$Email','$Calltime','$Comment') ";
mysql_select_db('hmintcwa_contacts');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully<br /><br /><a href=contactsadd.php><font color=#000000>Back</font></a>\n";
mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" name="ContactForm">
<table bgcolor="#000000" width="500" cellpadding="5" cellspacing="1" border="0">
<input type="hidden" name="Id" id="Id">
<tr>
<td bgcolor="#e9e9e9" align="right">Requested Info</td>
<td bgcolor="#ffffff" align="left"><select name="List">
<option value="0" > Please Choose One </option>
<option value="Market Analysis" > Market Analysis </option>
<option value="Consultation" > Consultation </option></select></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Date</td>
<input name="Date" type="hidden" id="Date" value="<? print(Date("l F d, Y")); ?>" />
<td bgcolor="#ffffff" align="left"><? print(Date("l F d, Y")); ?></td>
</tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Firstname</td>
<td bgcolor="#ffffff" align="left"><input name="Firstname" type="text" size="20" id="Firstname"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Lastname</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Lastname" size="20" id="Lastname"></td>
</tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Phone</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Phone" size="20" id="Phone"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Email</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Email" size="20" id="Email"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Preferred Calltime</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Calltime" size="20" id="Calltime"> If none put N/A</td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Comment</td>
<td bgcolor="#ffffff" align="left"><textarea name="Comment" cols="40" rows="8" id="Comment"></textarea></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right"> </td>
<td bgcolor="#ffffff" align="center"><br>
<input name="add" type="submit" id="add" value="Add Contact"><input type="reset" name="Reset" value="Clear Form"><input type=button value="Cancel" onClick="history.go(-1)"><br>
</td>
</tr>
</table>
</form>
<br> </center>
<?php
}
?>
</body>
</html>
So far I just keep chasing error message. Please forgive formatting I am trying to learn be gentle.
Your query arguments are backwards, and you should be using mysqli_. Here is the correct order.
$retval = mysqli_query($conn, $sql);
mysqli_query documentation
you need an end bracket for this statement: (if(!$error){)
edit: the } you were missing is actually a closing bracket for if(isset($_POST['add'])), not magic quotes. sorry!
//and so on...
if(!$error)
{
//add insert into database code here
// this probably won't run right...
// you're missing a ( after the word values...
// insert into tablename (id, name, stuff) values (1,'gloomy','stuff);
// this part of your statement is not correct: "VALUES'$Id,','$Date',
// and the commas are off, too.
$sql = "INSERT INTO contacts ".
"(`Id`,`Date`,`List`,`Firstname`,`Lastname`,`Phone`,`Email`,`Calltime`,`Comment`)".
"VALUES'$Id,','$Date','$List','$Firstname','$Lastname','$Phone','$Email','$Calltime','$Comment') ";
// print your SQL here to make sure it is correct.
// copy and paste it to run it directly in the DB. if it won't run there
// it won't run here
print $sql."<br/>";
mysql_select_db('hmintcwa_contacts');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully<br /><br /><a href=contactsadd.php><font color=#000000>Back</font></a>\n";
mysql_close($conn);
} // <-------- you're missing this closing bracket
} // this ends the statement for if(isset($_POST['add'])) { ....
else
{
// REMOVE this... or else it will print the world else somewhere
// i put this here to debug...
print "else<br/>";
?>
formatting your code helps a lot
EDIT: looking over the code, there's a lot of small issues everywhere. I'm not trying to be mean. I'm just saying... why don't you try to break the code up into smaller pieces and make sure all the parts will compile and work properly on their own before putting them all together? This is a lot to tackle all at once. Just try to dump your variables (arrays in particular) when you need to and each time you write a new chunk, make sure it works correctly and make sure everything else still works correctly. Then, move forward... it's easier to isolate problems that way.
this works for me. it uses pdo. oh, and now you don't need to worry about sql injection as much. this pretty much takes care of it completely. like everything, there's always ways around things but you do not need to check for magic quotes, you do not need to escape anything. doing the parameterization handles all that for you.
edit: so... when you write code... don't write a whole bunch of stuff and then see if it all works. write a few lines. test. write some more. test. make sure the new stuff works. make sure the old stuff still works. write a little more. i have absolutely no clue how you got that far with so many little issues. i'm not trying to be mean. write code in lil chunks, though. even logic. always test everything again, then move on.
and I left my debug statements in there... the print_r($array) and the var_dump(variable) so that you can see how that stuff is set up, where your values are coming from, what everything holds at whatever point, how to use them, where to put them. it will print weird things now. comment it out or remove them.
I understand there's a lot more tutorials for mysql_ functions but they are old and not safe at all. If you have issues using PDO, just come back to StackOverflow with your errors, issues and code and just write a disclaimer that "you know mysql_ functions are bad but the pdo is harder to learn" and people will be happy to help because it is that much better.
these are important PDO pages:
$stmt->bindParam()
$stmt->execute()
$stmt->rowCount() (I didn't use this but you might want it later)
$stmt->fetchAll() - for your select statements. this returns all the data in a huge array
how to prepare statements
and the code...
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
// include('inc_header.php');
function validate_Firstname($input, $pattern = "/([A-Za-z0-9])") {
return !preg_match($pattern, $input);
}
function validate_Phone($input, $pattern = "/([A-Za-z0-9])") {
return !preg_match($pattern, $input);
}
function isValidEmail($Email) {
return filter_var($Email, FILTER_VALIDATE_EMAIL);
}
// ====================================================================================
// ====================================================================================
if (!empty($_POST)) {
print "<pre>This is your \$_POST array \n\n".print_r($_POST,true)."</pre>";
}
$error = '';
if (isset($_POST['add']))
{
// require('dbcon.php');
$conn = new PDO('mysql:host=localhost;dbname=test', 'root', '');
// what if the array index ['whatever'] doesn't exist? errors.
// so we need to check and make sure it is set... then assign.
// this also gives us a blank default value, which is nice....
$id = isset($_POST['Id']) ? $_POST['Id'] : 'NULL';
$date = isset($_POST['Date']) ? $_POST['Date'] : '';
$list = isset($_POST['List']) ? $_POST['List'] : '';
$firstname = isset($_POST['Firstname']) ? $_POST['Firstname'] : '';
$lastname = isset($_POST['Lastname']) ? $_POST['Lastname'] : '';
$phone = isset($_POST['Phone']) ? $_POST['Phone'] : '';
$email = isset($_POST['Email']) ? $_POST['Email'] : '';
$calltime = isset($_POST['Calltime']) ? $_POST['Calltime'] : '';
$comment = isset($_POST['Comment']) ? $_POST['Comment'] : '';
if (!$list) {
$error .= "Please choose one<br />";
}
if (!$firstname) {
$error .= "First name is required<br />";
}
if (!$lastname) {
$error .= "Last name is required<br />";
}
if (!isValidEmail($email)) {
$error .= "The email entered is invalid<br />";
}
var_dump($error);
if (!$error)
{
$stmt = $conn->prepare("INSERT INTO contacts (id, date, list, firstname, lastname, phone, email, calltime, comment) \n".
" VALUES (:id, :date, :list, :firstname, :lastname, :phone, :email, :calltime, :comment) ");
$success = $stmt->execute(array(':id'=>$id, ':date'=>$date, ':list'=>$list, ':firstname'=>$firstname, 'lastname'=>$lastname,
':phone'=>$phone, ':email'=>$email, ':calltime'=>$calltime, ':comment'=>$comment));
if (!$success)
{
echo "\nPDO::errorInfo():\n";
print "<pre>".print_r($dbh->errorInfo(),true)."/<pre>";
}
else
{
print "it worked! the new row's ID is ".$conn->lastInsertId()."...!!!<br/>";
}
echo "Entered data successfully<br/><br/>";
} // end of if (!$error) { ... }
else
{
print "$error<br/>";
}
echo "<a href='contactsadd.php' style='font-color=#000000'>Back</a>\n";
} // end of if(isset($_POST['add'])) { ... }
else
{
// ====================================================================================
// ====================================================================================
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" name="ContactForm">
<table bgcolor="#000000" width="500" cellpadding="5" cellspacing="1" border="0">
<input type="hidden" name="Id" id="Id">
<tr>
<td bgcolor="#e9e9e9" align="right">Requested Info</td>
<td bgcolor="#ffffff" align="left"><select name="List">
<option value="0" > Please Choose One </option>
<option value="Market Analysis" > Market Analysis </option>
<option value="Consultation" > Consultation </option></select></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Date</td>
<input name="Date" type="hidden" id="Date" value="<?php print(Date("l F d, Y")); ?>" />
<td bgcolor="#ffffff" align="left"><?phpprint(Date("l F d, Y")); ?></td>
</tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Firstname</td>
<td bgcolor="#ffffff" align="left"><input name="Firstname" type="text" size="20" id="Firstname"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Lastname</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Lastname" size="20" id="Lastname"></td>
</tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Phone</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Phone" size="20" id="Phone"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Email</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Email" size="20" id="Email"></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Preferred Calltime</td>
<td bgcolor="#ffffff" align="left"><input type="text" name="Calltime" size="20" id="Calltime"> If none put N/A</td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right">Comment</td>
<td bgcolor="#ffffff" align="left"><textarea name="Comment" cols="40" rows="8" id="Comment"></textarea></td></tr>
<tr>
<td bgcolor="#e9e9e9" align="right"> </td>
<td bgcolor="#ffffff" align="center"><br>
<input name="add" type="submit" id="add" value="Add Contact"><input type="reset" name="Reset" value="Clear Form"><input type=button value="Cancel" onClick="history.go(-1)"><br>
</td>
</tr>
</table>
</form>
<br> </center>
<?php
}
?>

php registration mysql not a valid resource

Ok help..my registration page worked on the local server but its now saying that the two mysql lines are not valid when its online..why does it change when it goes online? the code pasted is all thats relevant. for some reason it doesnt like the transaction..and the email check mysql bit
include 'Connect.php'; //Connects to database
//When form is submit:-
if(isset($_POST['submit']))
{
// On submit, retrieve table values for php.
$Firstname = mysql_real_escape_string($_POST['firstname']);
$Surname = mysql_real_escape_string($_POST['surname']);
$Password = mysql_real_escape_string($_POST['password']);
$PasswordCheck = mysql_real_escape_string($_POST['passwordcheck']);
$Email = mysql_real_escape_string($_POST['email']);
$EmailCheck = mysql_real_escape_string($_POST['emailcheck']);
//CHECKS.
//Check username is available by retrieving any same values from the DB table.
$CheckEmailAvailable = mysql_query("SELECT * FROM 'user_details' WHERE Email = '$Email'");
echo $CheckEmailAvailable;
// $result = mysql_query("SELECT * FROM $tbl WHERE Email='$email' and LoginPassword='$password'");
$Results = mysql_fetch_array($CheckEmailAvailable);
//If Username field is blank.
if($Email == null )
{
echo "You must enter an email address.";
$url = htmlspecialchars($_SERVER['HTTP_REFERER']);
echo "<br/><br/>";
echo "<a href='$url'>Click Here To Return</a>";
die();
}
//If RESULTS is any value other than NULL, die.
if($Results != null )
{
echo "Email already taken. Please try another.";
$url = htmlspecialchars($_SERVER['HTTP_REFERER']);
echo "<br/><br/>";
echo "<a href='$url'>Click Here To Return</a>";
die();
}
//If Password and PasswordCheck fields in reg do not match, die.
if($Password != $PasswordCheck)
{
echo "The passwords you have entered do not match. Please try again.";
$url = htmlspecialchars($_SERVER['HTTP_REFERER']);
echo "<br/><br/>";
echo "<a href='$url'>Click Here To Return</a>";
die();
}
//If Password field is NULL (i.e. blank) die.
if($Password == Null)
{
echo "Your password must not be blank.";
$url = htmlspecialchars($_SERVER['HTTP_REFERER']);
echo "<br/><br/>";
echo "<a href='$url'>Click Here To Return</a>";
die();
}
//If Email and EmailCheck are not equal, die.
if($Email != $EmailCheck)
{
echo "The email addresses you have entered do not match. Please try again.";
$url = htmlspecialchars($_SERVER['HTTP_REFERER']);
echo "<br/><br/>";
echo "<a href='$url'>Click Here To Return</a>";
die();
}
//ELSE add data to DB.
else
{
//BEGIN TRANS
mysql_query("BEGIN TRAN");
//TABLE ADD.
$sql=mysql_query("INSERT INTO `user_details` (`Firstname`, `Surname`, `Email`, `Password`) VALUES ('$Firstname', '$Surname', '$Email', '$Password')")
or mysql_query("ROLLBACK TRAN") . die(mysql_error("Error registering, the database may be down, please try again later."));
//COMMIT transaction, to ensure data is added properly.
mysql_query("COMMIT TRAN");
header( 'Location: RegSucc.php' ) ;
}
} ?>
<html>
<!--Registration Form-->
<form name="form1" method="post" style="margin-left: 28%" action="Register.php">
<table width="100%" border="0" cellpadding="3" cellspacing="1">
<tr>
<td colspan="3"><strong>Register Account</strong></td>
</tr>
<tr>
<td style="width: 83px">First Name:</td>
<td>:</td>
<td><input name="firstname" type="text"/></td>
</tr>
<tr>
<td style="width: 83px">Surname:</td>
<td>:</td>
<td><input name="surname" type="text"/></td>
</tr>
<tr>
<td style="width: 83px">Email Address:</td>
<td>:</td>
<td><input name="email" type="text"/></td>
</tr>
<tr>
<td style="width: 83px">Email Address Confirmation:</td>
<td>:</td>
<td><input name="emailcheck" type="text"/></td>
</tr>
<tr>
<td style="width: 83px">Password:</td>
<td>:</td>
<td><input name="password" type="password"/></td>
</tr>
<tr>
<td style="width: 83px">Verify Password:</td>
<td>:</td>
<td><input name="passwordcheck" type="password"/></td>
</tr>
<tr>
<td style="width: 83px"> </td>
<td> </td>
<td><input type="submit" name="submit" value="Register"/></td>
</tr>
</table>
</form>
The query
SELECT * FROM 'user_details' WHERE Email = '$Email'
Is invalid. When denoting table names, it is good practice to use backticks, but using quotes will not work!
SELECT * FROM `user_details` WHERE Email = '$Email'
On your localhost, it may be setup to work with quotes. However, that is not the way it is "supposed" to be, and the server's installation may be different. Moral of the story: don't take shortcuts or use ugly code. Don't forget to backtick table names or columns, don't use PHP shorttags, etc.
$sql=mysql_query("INSERT INTO `user_details` (`Firstname`, `Surname`, `Email`, `Password`) VALUES ('$Firstname', '$Surname', '$Email', '$Password')")
should be
$sql=mysql_query("INSERT INTO user_details (Firstname, Surname, Email, Password) VALUES ('$Firstname', '$Surname', '$Email', '$Password')")
Also
SELECT * FROM 'user_details' WHERE Email = '$Email'
should be
SELECT * FROM user_details WHERE Email = '$Email'
that's it...
Change this line
$CheckEmailAvailable = mysql_query("SELECT * FROM 'user_details' WHERE Email = '$Email'");
to
$CheckEmailAvailable = mysql_query("SELECT * FROM user_details WHERE Email = '".$Email."'");
The problem is that when you moved to another server online (I can guess you were developing on Windows[which is case insensitive in MySQL], and your online server is Linux[case sensitive in MySQL]
If your string contains a variable to be evaluated and parsed, the use of single quotes around that variable name, within the double quote containing that string, is not so reliable most times. The best approach, (from personal experiences) is to do a concatenation.

Why does my form send the data twice after refresh?

I have a form in my website, but I can't fix one problem. When I write some text in the form box, it sends the data to the database. When I hit refresh, the page sends the same data again, to the database. What is the problem with my code?
<?php
if(isset($_POST['submit']))
{
$err = array();
$diss = $_POST['type'];
$sub = $_POST['sub'];
$msg = $_POST['msg'];
$uname = $_SESSION['uname'];
$date = "On " . date("F Y h:i:s A");
if (!isset($_SESSION['uname']))
$err[] = "You need to login";
else
{
if(empty($sub) && empty($msg))
$err[] = "All field required";
else
{
if(empty($sub))
$err[] = "Subject Requried";
if(empty($msg))
$err[] = "Message Requried";
}
}
if(!empty($err))
{
foreach($err as $er)
{
echo "<font color=red><b>$er</b></font>";
}
}
else
{
$sql= mysql_query("INSERT INTO discussion VALUES ('', '$diss', '$sub', '$msg', '$uname', '$date' ) ");
if(!$sql)
echo "Can't submit your discussion";
else
{
echo "Discussion was submitted";
}
}
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"
name="discussion">
<table width="240" border="0" cellspacing="0" cellpadding="0">
<tr>
<td style="width:230;"><b>Select your Discussion</b>
<select name="type">
<?php
$sqld = mysql_query("SELECT * FROM distype");
while($row = mysql_fetch_assoc($sqld))
{
$d_id = $row['d_id'];
$diss = $row['type'];
echo "<option value='$diss'>$diss</option>";
}
?>
</select></td>
</tr>
<tr>
<td><b>Subject</b></td>
</tr>
<tr>
<td><input type="text" name="sub" value="" size="33" class=""/></td>
</tr>
<tr>
<td><b>Message</b></td>
</tr>
<tr>
<td><textarea cols="30" rows="3" name="msg" class=""></textarea></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit Form"><br>
<td></td>
</tr>
</table>
On successful form submit you need to reload the url or redirect him somewhere to prevent user from inserting data to the database.
$sql= mysql_query("INSERT INTO discussion VALUES ('', '$diss', '$sub', '$msg', '$uname', '$date' ) ");
if(!$sql)
echo "Can't submit your discussion";
else
{
header("Location: page.php?mode=success");
//or
header("Location: ".$_SERVER['REQUEST_URI']); //which will just reload the page
}
The problem is, that your code will execute the same way when sent the same data. You need to protect against double inserts by one of many contructs:
Unique key on the table
Store hash of last post in session, refuse post if it has the same hash as stored
redirect user to different page on succes, so that a refresh will not cause the same POST

Categories