I have a code like this:
<body>
<?php
// define variables and set to empty values
$namaErr = $nikErr = $shiftErr = "";
$nama = $nik = $shift = $keterangan = $tgl = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["nama"])) {
$namaErr = "<br><i>Nama tidak boleh kosong</i>";
} else {
$nama = test_input($_POST["nama"]);
// cek nama harus pake huruf tanpa simbol
if (!preg_match("/^[a-zA-Z ]*$/",$nama)) {
$namaErr = "<br><i>Nama harus diisi dengan Huruf dan tanpa karakter simbol</i>";
}
}
if (empty($_POST["nik"])) {
$nikErr = "<br><i>NIK tidak boleh kosong</i>";
} else {
$nik = test_input($_POST["nik"]);
// cek nik harus pake angka tanpa simbol
if (!preg_match("/^[0-9]*$/",$nik)) {
$nikErr = "<br><i>NIK harus diisi dengan Angka</i>";
}
}
if (empty($_POST["keterangan"])) {
$keterangan = "";
} else {
$keterangan = test_input($_POST["keterangan"]);
}
if (empty($_POST["shift"])) {
$shiftErr = "<i>Pilih salah satu Shift Kerja</i>";
} else {
$shift = test_input($_POST["shift"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="container">
<form name="fmk" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
</html>
I want to send the form data to Proses.php to show the form data, but when I change the section form action from <form name="fmk" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post"> to
<form name="fmk" action="<?php echo htmlspecialchars(proses.php);?>" method="post"> or
<form name="fmk" action="proses.php" method="post">, it succeeds in submitting the form data to Proses.php, but the PHP code inside Proses.php fails to check the form data for validation. My objective is when I click the Submit button, it will go to another page and show the result from form data with PHP syntax when the input field is not empty. If some input fields are empty, it will show the red sign and not go to the other page (still on the first page).
Please help me to solve this problem.
Sorry for my bad english, Love from Indonesia :)
If you want the form validation on the client side to happen as (show the red sign if empty) you must add the required attribute to your input fields.In this way you can successfully check your form inputs and in addition if you want to set the input pattern for your input you can also use pattern attribute in your inputs.Both of these will validate your form on the client side.
Hope this might help you.
how to send form data to different .php file
There are a couple of ways to do this depending on how you want to process the information. You can use the form to send over post by setting your action attribute to the desired page. Setting the method attribute to post allows the name of the input fields to be carried over to that page through the server. On the target page you check the $_POST globals to make certain they are set and if they are set, you can then define them or call on their global variables in your code.
The way I do this on my target page is to first check if the submit button is set in the global POST array. If I have a button that submits my form and that name is name="submit" the $_POST will store that as a value in the global array.
if(isset($_POST['submit'])){
//submit is set, I can now check for the other values in the global $_POST array
if (empty($_POST["nama"])) {
$namaErr = "<br><i>Nama tidak boleh kosong</i>";
} else {
$nama = test_input($_POST["nama"]);
// cek nama harus pake huruf tanpa simbol
if (!preg_match("/^[a-zA-Z ]*$/",$nama)) {
$namaErr = "<br><i>Nama harus diisi dengan Huruf dan tanpa karakter simbol</i>";
}
}
}
If I have an issue here. For example I am testing and I know the things are set in the form, I can var_dump($_POST) and make certain that $_POST values are set by looking at the results of my $_POST array and checking the key/value pairs.
The other way to direct a user once they submit a form is by having the form action set to self or leaving your action attribute out completely. You can check if the submit button is set and then parse through the global $_POST array within the if(isset($_POST['submit])){ //form has been submitted check inputs, run validations and set errors, etc, etc... } conditional. You can do all the work on the same page the form is on using this method and then once all has been successfully completed use a header redirect to send the user to the desired page you wish for them to visit with a success url post.
It would be something to the effect:
if(isset($_POST['submit'])){
if(isset($_POST['name'])){
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$msg = "Success, thank you for submitting";
// maybe check validation of inputs and run other inputs through sanitation etc...
// once you finish your checks if all is good set your url params
$host = $_SERVER['HTTP_HOST']; // sets your server name
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); // PHP_SELF
$root = 'proses.php';
$urp = '?success';// adds a url post to your url and this can be checked on the other page
header("Location: http://$host$uri/$root$urp");
exit;
}else{
// run error code here
$error = true;
$msg = "Error please try again";
}
}
Related
I'm creating a form that applies the CRUD functions using HTML/PHP and mySQL. I'm able to delete, read, and update but am unable to create a new record. Below is my database structure, index page, and create page. Any guidance appreciated. I did not include the config file because I did not find it necessary. The name of the database Thanks!
exact error
Notice: Undefined index: rank in C:\xampp\htdocs\Update\create.php on line 30
create.php
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$nickname = $lastsubmission = $rank = "";
$nickname_err = $lastsubmission_err = $rank_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate name
$input_nickname = trim($_POST["nickname"]);
if(empty($input_nickname)){
$nickname_err = "Please enter a name.";
} elseif(!filter_var($input_nickname, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[a-zA-Z\s]+$/")))){
$nickname_err = "Please enter a valid name.";
} else{
$nickname = $input_nickname;
}
// Validate address
$input_lastsubmission = trim($_POST["lastsubmission"]);
if(empty($input_lastsubmission)){
$lsstsubmission_err = "Please enter an address.";
} else{
$lastsubmission = $input_lastsubmission;
}
// Validate salary
$input_rank = trim($_POST["rank"]);
if(empty($input_rank)){
$rank_err = "Please enter the salary amount.";
} elseif(!ctype_digit($input_rank)){
$rank_err = "Please enter a positive integer value.";
} else{
$rank = $input_rank;
}
Your nickname element in the HTML form needs the name attribute. Likely a copy/paste error?
Same applies to all your other HTML input elements.
Change nickname="nickname" to name="nickname".
<input type="text" name="nickname" class="form-control" value="<?php echo $nickname; ?>">
It's because you assign $param_nickname after you bind it with mysqli_stmt_bind_param
//First Set parameters
$param_nickname = $nickname;
$param_lastsubmission = $lastsubmission;
$param_rank = $rank;
//Then Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "sss", $param_nickname,
$param_lastsubmission, $param_rank);
should do the trick
Nothing happens when you click the submit button at the bottom of the page. I simply want it to validate user input and I am only focused on the name field at the moment and I cannot get it to validate any input in the name field. No error messages pop up or anything. Please review this and offer any suggestions, I cannot find my error.
PHP portion, where variables are initialized and set to empty. As well as the post methods and isset functions
<?php
//define variables and set them to empty values
$fname_error= $phone_error= $address1_error= $address2_error= $city_error= $state_error= $zipcode_error= "";
$fname= $phone= $address1= $address2= $city= $state= $zipcode= "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$fname_error = "Missing";
}
else {
$fname = test_input($_POST["fname"]);
//now we check to see that the name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
$fname_error = "Please use letters and white space only";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
The Html portion:
<div class="userinput">
<label for="fname"><b>First Name</b></label>
<input type="text" name="fname" value="<?php
echo $fname ?>">
<span class="error">
<?php echo $fname_error;?></span>
</div>
Good day. This is just a hypothesis, I may be wrong as I couldn't check the entire code, but you cannot have more than 1 form on the same page. Because, you need a single opening and closing form tag that wraps ALL form elements on your page. Form fields are only counted as part of a form if they are contained within the form elements. And you do have more than 1 form on the same page.
Also, you should consider minimizing your code to only what's needed.
Hope this helps!!!
Here is the code for registration. Values are inserted properly but page is not redirected to another page:
if(isset($_POST['submit'])){
$company_name = $_POST['company_name'];//check whether form is submitted or not
$email = filter_var($_POST['email'],FILTER_SANITIZE_EMAIL);//email validation
$password = sha1($_POST['password']);
$phone = $_POST['phone'];
$city = $_POST['city'];
$profession = $_POST['profession'];
check validation of email
if(!filter_var($email,FILTER_SANITIZE_EMAIL)){
echo 'invalid email';
}
else
{
$result = mysql_query("SELECT * FROM registerpro WHERE email = '$email'");selecting email from database
$data = mysql_num_rows($result);//check if there is result
if($data==0){
$qry = mysql_query("INSERT INTO registerpro (company_name,email,password,phone,city,profession) VALUES ('$company_name','$email','$password','$phone','$city','$profession')");
here i is the problem as page is not redirecting to another page so please tell me how to fix it
if($qry){
header("Location : company_info.php");//redirect to company_info
}
else`enter code here`
{
echo 'error';
}
}else{
echo 'invalid email';
}
}
}
?>
After registration page is not redirecting to company_info.
Remove extra space after Location
So, change
header("Location : company_info.php");//redirect to company_info
To:
header("Location: company_info.php");//redirect to company_info
// ^ here
I finally figured this out after struggling a bit. If you perform a web search on the PHP header() function you will find that it must be used at the very top of the file before any output is sent.
My first reaction was "well that doesn't help", but it does because when the submit button is clicked from the HTML input tag then the header() function will get run at the top.
To demonstrate this you can put a section of PHP code at the very top with the following line...
print_r($_POST);
When you then press the "Submit" button on your web page you will see the $_POST value change.
In my case I wanted a user to accept the Terms & Agreement before being redirected to another URL.
At the top of the file before the HTML tag I put the following code:
<?php
$chkboxwarn = 0;
/* Continue button was clicked */
if(!empty($_POST['continue']) && $_POST['continue']=='Continue'){
/* Agree button was checked */
if(!empty($_POST['agree']) && $_POST['agree']=='yes'){
header('Location: http://www.myurlhere.com');
}
/* Agree button wasn't checked */
else{
$chkboxwarn = 1;
}
}
?>
In the HTML body I put the following:
<form method="post">
<input type="checkbox" name="agree" value="yes" /> I understand and agree to the Terms above.<br/><br/>
<input type="submit" name="continue" value="Continue"/>
</form>
<?php
If($chkboxwarn == 1){
echo '<br/><span style="color:red;">To continue you must accept the terms by selecting the box then the button.</span>';
}
?>
What I want is to show the error (message), only if the user do a false action. For example, if the field is empty, it will show (Please fill all the fields). I've already done that, but the problem that I have is that it shows also if the user enter to the page for the first time, meaning it does NOT respects the (if condition) that I have written !
The question :
How to show the message only if one of the fields is empty ?
Any ideas on how I can solve it ?
Here is my code :
<?
$conn = mysqli_connect('localhost', 'db', 'db_pass', 'db_name') or die("Error " . mysqli_error($conn));
$email = filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL);
$old_password = trim($_POST['old_pass']);
$new_password = trim($_POST['new_pass']);
$email = mysqli_real_escape_string($conn,$email);
$old_password = mysqli_real_escape_string($conn,$old_password);
$new_password = mysqli_real_escape_string($conn,$new_password);
if(empty($email) || empty($old_password) || empty($new_password)){
echo 'Please fill all the fields !<br>';
}
else{
$sql="UPDATE users SET pass='$new_password' WHERE email='$email' AND pass='$old_password'" or die("Error " . mysqli_error($conn));
$result = mysqli_query($conn,$sql);
mysqli_close($conn);
}
if($result){
echo'Password changed successfully !';
}
elseif(!$result) {
echo 'The email/password you provided is false !';
}
?>
Validation of any form happens in the "action" file within a condition i.e. the validation should be subjected to the event of user clicking the submit button. For this to work you should check that
1. Your form has a submit button with a name property set to say submit (can be anything)
eg: <input type="submit" name="submit" id="someid" value="Submit" />
2. The form must have action property pointing to a processor file
eg: <form action = "somefile.php" method = "post">
3. In the somefile.php file the validation code must be within a condition which checks for the event of form been submited
eg://somefile.php
<?php
if(isset($_POST['submit']{
//all the validation code goes here
}else{
//for a single page form and validation
// the code for displaying the form can go here
?>
I suggest you to do this:
First define a variable with plain $_POST[] for eg $name = $_POST['name'];
Then, check if all the vatiables you've define are empty or not.
Lastly, Use escape_string() or whatever you want.
The solution is to check for a variable that you know will always be set if the form is submitted, usually the submit button.
For example, if your form ends like this:
...
<input type="submit" name="change_password" value="Change password" />
</form>
then in the PHP code you could check
if(isset($_POST['change_password'])) {
// The submit button was in the POSTed data, so this is a form submit
} else {
// This is a new page load
}
Alternatively, if you are POSTing the data, you can check which HTTP method was used to call the form:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Form was posted
} else {
// $_SERVER['REQUEST_METHOD'] == 'GET'
}
The pattern I commonly use is:
$showForm = true;
if( is_form_postback() ) {
if( data_is_valid() ) {
redirect_to_thank_you_page();
} else {
show_validation_errors();
$showForm = false;
}
}
if($showForm) {
// Print the form, making sure to set the value of each input to the $_POSTed value when available.
}
I have a PHP form that I've set up with a POST method. When all the fields aren't filled out I have a Javascript alert box that pops up and states 'Please fill out all fields!' When I click 'OK' on the alert window it reloads the form behind it clearing all the data that was entered. Is there a function that can keep the alert box's OK button from reloading the entire page? Here's my code:
<?php
if (isset($_POST['brandname']) && isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['email']) && isset($_POST['website'])){
$brandname = $_POST['brandname'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$website = $_POST['website'];
if(!empty($brandname) && !empty($firstname) && !empty($lastname) && !empty($email)){
$to = 'matt#miller-media.com';
$subject = 'Submission Form';
$body = $firstname;
$headers = 'From: '.$email;
if (#mail($to, $subject, $body, $headers)){
}
}else{
echo '<script type="text/javascript">
window.alert("Please fill out all fields!")
</script>';
}
}
?>
You are alerting your user after posting response ... in this case I would re-post the whole form again with its values set to $_POST or variables that were set using it, for example :
<input type='text' name='brandname' value='<?php echo $_POST['brandname'];?>' />
or :
<input type='text' name='brandname' value='<?php echo $brandname; ?>' />
and so on
But in this case I recommend using client-side validation on the form (Using javascript)
Yeah i assume you need something like this:
<script type="text/javascript">
function do_some_validation(form) {
// Check fields
if (! /* Contition 1 */ ) return false;
if (! /* Contition 2 */ ) return false;
if (! /* Contition 3 */ ) return false;
form.submit();
}
</script>
<form onsubmit="do_some_validation(this) return false;" action="script.php" method="post">
// Fields
</form>
This will only submit the form once all JavaScript conditions in do_some_validation are met... Please note this is not advised over and above PHP validation, this should be used purely for comfort for the user not having to submit the page when there's something Javascript can validate against
For any further PHP validation messages, you can either pass variables into GET or SESSION, eg.
<?php
session_start();
if (count($_POST)) {
if (!/* Condition 1 */) $_SESSION['error'] = "Message";
if (!isset($_SESSION['error'])) {
// Proceed
} else header("Location: script.php");
}
?>
On the page:
<?php if (isset($_SESSION['errir'])) {
echo $_SESSION['error'];
unset($_SESSION['error']);
} ?>
Since your code sample is PHP-code, it seems that you are posting the form and validate it server-side, and then you show an alert if any field is empty? In that case, the page has already reloaded, before the alertbox is shown. You are mixing server-side and client-side code.
If you want to show an alert box if the user hasn't filled in all the fields (without reloading the page), you will have to do the validation with JavaScript. You should still keep your PHP-validation as well though!
If you use jQuery for instance, you could do something like this:
$("#your-form-id").submit(function(){
// Check all your fields here
if ($("#input-field-1").val() === "" || $("#input-field-2").val() === "")
{
alert("Please fill out all fields");
return false;
}
});
It can of course be done without jQuery as well. In that case you can use the onsubmit attribute of the form tag to call a JavaScript function when the form is posted, and within that function you do the validation of the form, show an alert box if any field is empty, and then return false from the function to prevent the form from being posted to the server.