Whenever I entered value first time and add record its added perfectly but whenever I refresh my browser by pressing F5 it shows message
"the page that you're looking for used information that you entered..." and insert duplicate record.
HTML code define below:
<?php include("Connection.php"); ?>
<form role="form" method="post">
<div class="col-md-6">
<div class="form-group">
<label>Type Name</label>
<input name="emptype" class="form-control" placeholder="Employee ID">
</div>
<div class="form-group">
<label>Type Description</label>
<input name="typedecs" class="form-control" placeholder="First Name">
</div>
</div>
<div class="col-md-12 text-right">
<button type="submit" name="addtype" class="btn btn-primary">Add Type</button>
<button type="reset" class="btn btn-default">Reset</button>
</div>
</form>
below is my PHP Code
<?php
$emptype=$_POST['emptype'];
$typedesc=$_POST['typedecs'];
if(isset($_POST['addtype']))
{
$query=mysql_query("insert into emptype(typename,typedesc)values('$emptype','$typedesc')")or die("<script>alert('Error');</script>");
echo '<script>showAlert();window.setTimeout(function () {HideAlert();},3000);</script>';
Does something i missing? Please Help.
suggestion: use mysqli_* or PDO instead of mysql_* functions, but you have written code in it so i gave the code also in it.
Just run a select query to check if the record already exists in database if exists then do not insert it again.
$query=mysql_query("SELECT * FROM emptype WHERE typename = '$emptype' AND typedesc='$typedesc') or die(mysql_error());
if (mysql_num_rows($query)<=0)
{
$query=mysql_query("insert into emptype(typename,typedesc)values('$emptype','$typedesc')")or die("<script>alert('Error');</script>");
}
One option could be to Test if the value is already in your database.
Source : example from PHP.net - mysql_query
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT * FROM emptype
WHERE typename='%s' AND typedesc='%s'",
mysql_real_escape_string($emptype),
mysql_real_escape_string($typdesc));
// Perform Query
$result = mysql_query($query) or die(mysql_error());
// Get num rows
$num_rows = mysql_num_rows($result);
// If $num_rows is False - It's not a duplicate
if(!$num_rows)
...
Consider using PDO PHP.net - PDO - mysql functions are depreciated.
i think it is because the php script (insert query) is at the same page of the HTML form, so when you refresh the page you tell the browser to call the php script again with previous data. so to prevent that separate the HTML form from the php so you code should be like:
1- HTML.php
<?php include("Connection.php"); ?>
<form role="form" method="post" action="Action.php">
<div class="col-md-6">
<div class="form-group">
<label>Type Name</label>
<input name="emptype" class="form-control" placeholder="Employee ID">
</div>
<div class="form-group">
<label>Type Description</label>
<input name="typedecs" class="form-control" placeholder="First Name">
</div>
</div>
<div class="col-md-12 text-right">
<input type="submit" value="submit">
</div> </form>
2- Action.php
<?php include("Connection.php");
$emptype=$_POST['emptype'];
$typedesc=$_POST['typedecs'];
if(isset($_POST['addtype']))
{
$query=mysql_query("insert into emptype(typename,typedesc)values('$emptype','$typedesc')")or die("<script>alert('Error');</script>");
echo '<script>showAlert();window.setTimeout(function () {HideAlert();},3000);</script>'; echo "<meta http-equiv='refresh' content='0;url=html.php'>";
?>
this will make html.php page call Action.php page when the submit button is pressed then the php script will be executed then it will redirect you to the html.php page again
Related
I have a form with some textbox that loads the data from the database. I have created also a button where I can update the data but currently it's not working and I don't have any clue why.
Here's my query:
<?php
include('connect.php');
if (isset($_POST['btnUpdate'])){
$query = "UPDATE users SET fname = '".$_POST['fname']."', lname = '".$_POST['lname']."' WHERE user_id = '".$_POST['id']."'";
$result = mysql_query($query);
if ($result) {
die("<strong>Updated</strong>");
} else {
die("<strong>Error ".mysql_error()."</strong>");
}
}
?>
Here's my form:
<form class="form-horizontal" role="form" action="" method="post">
<input type="hidden" name="id" value="<?php echo $row['user_id']; ?>"/>
<div class="form-group">
<label class="col-lg-3 control-label">First name:</label>
<div class="col-lg-8">
<input class="form-control" name="fname" type="text" value="<?php echo $row['fname'];?>">
</div>
<label class="col-lg-3 control-label">Last name:</label>
<div class="col-lg-8">
<input class="form-control" name="lname" type="text" value="<?php echo $row['lname'];?>">
</div>
<label class="col-md-3 control-label"></label>
<div class="col-md-8" >
<input type="button" name="btnUpdate" class="btn btn-primary" value="Save Changes">
<span></span>
<input type="reset" class="btn btn-default" value="Cancel">
</div>
</div>
</form>
I've tried everything but it won't update my database. It doesn't have any error whatsoever when I checked it on the browser. I'm running out of ideas. Anyone know what part of my code is wrong? I'm still a beginner to php and I cannot seem to understand what's wrong here. Any ideas how to solve this problem would be greatly appreciated. Thanks
Posting as a community wiki; I feel no rep should come of it.
<input type="button"> does not by default propagate POST. Therefore you either need to use a "submit" type:
Either <input type="submit"> or <button type="submit">.
References:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/button
type
The type of the button. Possible values are:
submit: The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.
reset: The button resets all the controls to their initial values.
button: The button has no default behavior. It can have client-side scripts associated with the element's events, which are triggered when the events occur.
You're also open to a serious SQL injection if your site is live or intended to go live.
You should start looking into switching over to either the mysqli_ or PDO api and with a prepared statement.
References:
http://php.net/manual/en/mysqli.prepare.php
http://php.net/manual/en/pdo.prepared-statements.php
https://en.wikipedia.org/wiki/SQL_injection
I have a Bootstrap form and after complete the form I want remain in the same page and display a thank you message just below the submit button.
Here my HTML code
<div id="form">
<div class="row">
<div class="col-md-12"><h3>RESTA IN CONTATTO</h3>
<form id="form_members" role="form" data-toggle="validator" novalidate action="form-data.php" method="POST">
<div class="form-group">
<label for="firstname" class="control-label">Nome</label>
<input type="text" class="form-control" name="firstname" id="name" placeholder="Inserisci il Nome" required>
</div>
<div class="form-group">
<label for="lastname" class="control-label">Cognome</label>
<input type="text" class="form-control" name="lastname" id="lastname" placeholder="Inserisci il Cognome" required>
</div>
<div class="form-group">
<label for="email" class="control-label">Email</label>
<input type="email" class="form-control" name="email" id="email" placeholder="Enter the Email" data-error="Inserire email valida" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<div class="checkbox">
<label>
<input type="checkbox" id="terms" required data-error="Devi essere d'accordo con i termini di condizione d'uso">Privacy
</label>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" name="submit" id="submit" onclick="this.form.clear()" value="submitmessage">Registrati</button>
</div>
</form>
<div id="submitmessage"></div>
and Here my php Code
<?php
$link = mysqli_connect("","","") or die("failed to connect to server !!");
mysqli_select_db($link,"");
if(isset($_POST['submit']))
{
$errorMessage = "";
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$email=$_POST['email'];
// Validation will be added here
if ($errorMessage != "" ) {
echo "<p class='message'>" .$errorMessage. "</p>" ;
}
else{
//Inserting record in table using INSERT query
$insqDbtb="INSERT INTO `test`.`members`
(`firstname`, `lastname`, `email`) VALUES ('$firstname', '$lastname', '$email')";
mysqli_query($link,$insqDbtb) or die(mysqli_error($link));
}
}
?>
First check if your insert actually happen by assigning result to a variable, ie:
$res=mysqli_query($link,$insqDbtb);
Now, below your form you can add the following php code and you can use this variable in an if statement to echo different things:
if($_POST && $res)
{/*this code is executed if form is submitted and insert worked*/
echo ' <div class="alert alert-success" role="alert">
Grazie per esserti registrato!
</div>';
}
elseif ($_POST && !$res)
{ /*you can write a different message if insert did not happen*/
echo '<div class="alert alert-danger" role="alert">
<strong>Oh no!</strong> Provaci ancora
</div>';
}
Note that this might only work if you use php to process the form and scripts are on the same page so you would also need to modify your form like this:
<form action="register.php" method="post" accept-charset="utf-8">
(where register.php stands in for the name of your file)
and the submit button like this:
<input type="submit" name="submit" value="Submit" id="submit_button" class="btn btn-primary" />
Then at the top of your page, after you have set the parameters for the connection you put the following statement:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
and you can put all the form validation here. What happens is the first time you go to the file it will be through a GET so nothing happens, after you submit the form you access the same file but with a POST so the submission is validated.
To submit the form and stay on the same page you have two possibilites:
A) As other people have suggested you use Ajax
B) The other possibility which has the same visible result for the user is that when you submit your form you go back to the same page, so the user will see the same page but different things will be displayed depending on weather he has already submitted the form or not
To achieve this second solution you can do the following:
1)In your head you establish the connection (the php you have is improvable but as a first attempt should do the job)
2) In your page you put your form with the following modification:
<form action="FILNAME.php" method="post" accept-charset="utf-8">
and
<input type="submit" name="submit" value="Submit" id="submit" class="btn btn-default" />
THis way when a user clicks the button the form is submitted to the same page.
3) Now you need to check if your page is beening accessed for the first time (ie thoruh a GET) or after the form has been submitted, so where you want your message to appear you put the following if statement:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
}
3) Within this bracket you put all your php to validate the form and after validation your insert command
$insqDbtb="INSERT INTO `test`.`members`(`firstname`, `lastname`, `email`) VALUES ('$firstname', '$lastname', '$email')";
$res = mysqli_query($link, $insqDbtb);
4) If the query created a new row you can write the thank you message:
if (mysqli_affected_rows($link) === 1) {echo '<div class="alert alert-success"><h3>Thanks!</h3><p>Thank you for registering! </p></div>';
If not you can write an alert instead
I learned this method from a book by Larry Ullman, you can find the scripts with examples for free
here
I want two dates if I post start date and end date from submit form. I have attendance record table. I want to retrieve this table. How can I do that?
This is my code. It redirects to test.php. How can I retrieve another page? Who can help me kindly?
<form method="post" class="form-horizontal" role="form" action="test.php">
<!--Start Date-->
<div class="col-lg-12">
<div class="form-group required">
<label for="startdate" class="control-label">Start Date:</label>
<input class="form-control" placeholder="Choose Date " type="text" id="datepicker-8" name="startdate" required="required" />
</div>
</div>
<!--End Date-->
<div class="col-lg-12">
<div class="form-group required">
<label for="enddate" class="control-label">End Date:</label>
<input class="form-control" placeholder="Choose Date " type="text" id="datepicker-9" name="enddate" required="required" />
</div>
</div>
<!--Create Button-->
<div class=""> <br/>
<input class="btn btn-success" type="submit" value="Search" />
</div>
</form>
You need to first get both start date and end date in vairable using $_REQUEST like that way.
$start_data = $_REQUEST['startdate'];
$end_data = $_REQUEST['enddate'];
Now you need to use sql query to fetch data from table :
$query = mysql_query("select * from table_name where startdate='$start_data' AND enddate='$end_data'");
while($row=mysql_fetch_array($query)) {
// Print your variable here
}
in test.php:
<?php
var_dump($_POST);
Then submit your form. You will see all the fields and values that were contained in the form. You can access individual fields like so: $startdate = $_POST['startdate']
Good luck!
When you click the submit button the page will be redirected to test.php file, the content which you will write in test.php will be shown. Now to retrieve date from post u can use $startdate=$_POST['startdate'] simillarly for $enddate=$_POST['enddate']. After this use queries to fetch the data from database using the startdate and enddate variable
after many days of trying to get a previously working php form converted to submitting the variables inside a new div I realized that I'm missing something. Other posts show javascript, but Iv'e never used that before and don't understand the need. The new page draws correctly, but the php variables are not being received on the destination page.
HTML for the submit,
<form action="entrance2.php">
<div class="medium-12 columns m-b20"><h4 class="heading">Existing users log-in here :-</h4></div>
</div>
<div class="row">
<div class="user medium-12 columns text-center m-b15"><img src="images/user-img.png" alt=""/></div>
</div>
<div class="row">
<div class="medium-10 columns medium-offset-1"><label for="User Name"></label>
<input id="OwnerEmaili" type="text" placeholder="User Name" name="UserName"></div>
</div>
<div class="row">
<div class="medium-10 columns medium-offset-1"><label for="Password"></label>
<input id="OwnerPasswordi" type="password" placeholder="Password" name="Password"></div>
</div>
<div class="row">
<div class="medium-12 columns text-center"><button class="grd-button">Log In</button></div>
<input type="submit" id="save" name="save" value = "Submit"/>//simple submit for testing
<div class="grd-button1" onClick="document.forms['submit-form'].submit();"></div>
</form></div>
</div>
</div>
Receiving page,
<?php
$p_OwnerEmaili=$_POST["OwnerEmaili"];
$p_OwnerPasswordi=$_POST["OwnerPasswordi"];
echo "$p_OwnerEmaili;$p_OwnerPasswordi";
Only shows the ;.
Is javascript required to submit from inside a div?
You're accessing the wrong items.
You'll need to set your forms input name attributes to this if you want to access them the way you currently have in your php script:
<input id="OwnerEmaili" type="text" placeholder="User Name" name="OwnerEmaili">
And
<input id="OwnerPasswordi" type="password" placeholder="Password" name="OwnerPasswordi">
That will allow you to access them as you do in your PHP script.
You can always check what values have been sent to your php script by using var_dump() or print_r().
<?php print_r($_POST); ?>
Would've shown you that you had UserName & Password set instead of what you wanted.
As Ghost pointed out in the comments, your form will always send user input via GET if you dont specify a method in it. So set this in your form tag:
<form action="entrance2.php" method="post">
I've made a html form using Bootstrap. I've used "required" to ensure data is populated in certain fields for the form to be submitted. This form goes to a php script that opens a database connection, inputs the values as per form submitted, directs to a thank you page and closes the connection.
Its my first hand coded form and my concern is security. How do I keep hackers/spammers at bay?
Can you point out, please, issues with my code so I can address them before I put this live. Please be gentle, Im a newbie with about 3 months of coding experience.
Please note the original form actually has 9 fields but I've omitted it presuming those details wont be necessary for this discussion.
HTML Code
<form class="form-horizontal" method="post" action="vacancy.php">
<div class="form-group">
<label for="company" class="col-sm-3 control-label">Company Name *</label>
<div class="col-sm-6">
<input type="text" name="company" class="form-control" placeholder="Enter Company Name" required />
</div>
</div>
<div class="form-group">
<label for="contactperson" class="col-sm-3 control-label">Contact Person *</label>
<div class="col-sm-6">
<input type="text" name="contactperson" class="form-control" placeholder="Enter Full Name" required />
</div>
</div>
<div class="form-group">
<label for="designation" class="col-sm-3 control-label">Designation *</label>
<div class="col-sm-6">
<input type="text" name="designation" class="form-control" placeholder="Enter Designation" required />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Clear</button>
</div>
</div>
</form>
PHP Code
<?php
$con=mysqli_connect("localhost","db2u","password","db2");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO vacancy (Company, ContactPerson, Designation)
VALUES
('$_POST[company]','$_POST[contactperson]','$_POST[designation]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
header("Location: thankyou.html");
mysqli_close($con);
?>
EDIT : So it seems I need validation. Im looking at jqBootstrapValidation. Even considering htmlspecialchars (which ever is easier). I believe both would do an equally good job right? PDO is a bit too much for me at the moment.
Your code could be compromised by SQL injection http://en.wikipedia.org/wiki/SQL_injection.
Try use htmlspecialchars or better use PDO instead of OLD and DANGEROUS mysql_* functions.
You have not validated any field in your php code,
you should put validation in php file too, any user can remove "required" from input and can post the data.
Never trust the user input. You should escape the strings with mysqli_real_escape_string() function.
http://www.php.net/manual/en/mysqli.real-escape-string.php
$company = mysqli_real_escape_string($_POST[company]);
$contactperson = mysqli_real_escape_string($_POST[contactperson]);
$designation = mysqli_real_escape_string($_POST[designation]);
$sql="INSERT INTO vacancy (Company, ContactPerson, Designation) VALUES ('$company','$contactperson','$designation')";