How to display empty field error message - php

I have a page which allows the user to "create a topic", open submitting this the form goes to another through a verification process which inserts the topic into the database and re-directs to back to the main page. However I want my verification page "add topic" to display an error message if all fields are not filled in. here is a my code, please can you tell me where I would need to add this validation code to notify the user to fill all fields:
// get data that sent from form
$topic=$_POST['topic'];
$detail=$_POST['detail'];
$name=$_POST['name'];
$email=$_POST['email'];
$datetime=date("d/m/y h:i:s"); //create date time
$sql="INSERT INTO $tbl_name(topic, detail, name, email, datetime)VALUES('$topic', '$detail', '$name', '$email', '$datetime')";
$result=mysql_query($sql);
if($result){
echo "Successful<BR>";
echo "<a href=main_forum.php>View your topic</a>";
}
else {
echo "ERROR";
}
mysql_close();

My suggestion would be create a separate php file called validation and inside the validation file add a function. Of course you can create this function inside the same php file. If you made the separate use an include statement to place it on your page. Also a quick post-back to itself would be good since you could easily be able to get access to the posted variables and already be on the page to show errors. Otherwise you would have to return the Errors in a get, post or session. If everything was successful you could post or redirect right after the postback (maybe to a success page) and the user would only see the postback if errors present.
include_once("Validation.php");
as shown above.
validateNewTopic($topic, $detail, $name, $email, $datetime)
{
}
Then inside you could use if statements to check conditions. If you want a quick solution you can create a variable to hold all the errors.
$Error = "<p class='errors'">;
if ($topic == "")
{
$Error+="topic is required";
}
if ($Error != "<p class='errors'">)
{
return $Error +"</p>";
}
else
{
return "";
}
Since you are posting the values you can catch them in a variable on postback to validate.
$topic = $POST['topic'];
$Error=validateNewTopic($topic);
if ($Error != "")
{
?>
echo $Error
<?php
}
else {
//run sql code and show success
}
By putting the paragraph tags inside the $Error messages we can just echo and it will already be in the paragraph tag with the class errors. You can make it prettier by using an un-ordered list and when adding an error using list items. I'm not sure how familiar you are with php but at anytime you can stop writing php code by closing the tags. (< php ?> and reopen < ? php) as shown above in the if statement. I know this was not 100% clear but this is something you should try/research and practice since it is used so often. Good luck!

You can send the error to the main page by using php GET request, and then display it.

Related

How to go to new page on form submit only if form passes error checks?

I have an HTML form with PHP error checks. The form has several different types of fields (one for name, email, phone number, a checkbox, a drop down, etc.) and I have a PHP function written for each that runs when you hit the submit button, and checks that the form is filled in correctly and fully. If a field is left empty, or is filled in incorrectly, an error message appears. However, after I got that running, I tried to add a redirect, so that after the form is completed and submit is pressed, it brings the user to a confirmation page, if the errorchecks are passed. I wrote it like this:
if(isset($_POST['submit']) ){
header("Location:confirmed.php");}
It does what it's supposed to--bring the user to a new page--but it doesn't take into consideration any errorchecks. So, when submit is pressed, rather than run through the error checks, it immediately goes to the new page. I tried adding a variable named "errorcount" so each function so that the number of errors that occur when the form is submit will be either counted, or removed from the count, and then considered when changing the page...
if(isset($_POST['submit']) ){
if ($errorcount == 0){
header("Location:confirmed.php");}}
This didn't work either. I realized that $errorcount wasn't actually being updated at all; for what reason, I'm not sure. I set it up so each function returns $errorcount, and then called each function in the snippet of code above before running the second if statement, but it still does nothing.
I feel like I'm approaching this the wrong way, but I'm not really sure how else to do this. Please tell me if there's an easier way to achieve this, or maybe you have an idea what I'm doing wrong in the first place.
EDIT:
I am passing the variable $errorcount as global in each function, like so:
function validateName ($name, $submit){
global $errorcount;
if( empty( $submit )) {
return '';}
if (empty ($name)){
return "You didn't enter your name!";
$errorcount = $errorcount+1;
}
if (!preg_match("/^[a-zA-Z \-]*$/",$name, $matches)){
return "Please enter a valid name";
$errorcount = $errorcount+1;
}
else{
$errorcount = $errorcount-1;
}
return $errorcount;
}
However, $errorcount still does not actually change with the if loop I posted above. If I take that out (the section of code that causes the page to change) then the functions work as intended; once you click submit, the page refreshes, and error messages appear where the user did not fill out the form properly. But once all the form areas are filled out properly, clicking submit does... nothing.
EDIT 2:
I got it working. It's honestly not very efficient but it does what I need it to do. Thanks to all who helped!
You don't really need to count the errors, and you don't need to use global. Just write your validator functions so they return an error message if there is an error, or nothing if there is no error. Like this, for example:
function validateName($name) {
if (!$name) {
return 'name is required';
}
if (!preg_match("/^[a-zA-Z \-]*$/", $name)) {
return "Please enter a valid name";
}
}
Then when you run your validators, add any error messages you get to an array.
if ($error = validateName($_POST['name'] ?? '')) {
$errors['name'] = $error;
}
After you run all the validators, if the error array is empty, then there were no errors so you can redirect. And if it's not empty, then you have an array of errors keyed by field name, so you can display any errors next to the problematic fields, which your users will prefer rather than getting one error at a time in some generic location.
if (empty($errors)) {
// redirect
} else {
// stay here and show the errors
}
You're needlessly complicating things. Defining functions are only useful if you plan on re-using that code elsewhere. Try this instead:
if ( isset($_POST['submit']) )
{
if ( empty($name) )
{
echo "You didn't enter a name!";
sleep 3;
// redirect or re-load the form
}
elseif ( !preg_match("/^[a-zA-Z \-]*$/", $name, $matches) )
{
echo "Enter a valid name!";
sleep 3;
// redirect or re-load the form
}
header("Location:confirmed.php");
}

Five unique pages lead to one page. Can I change the <h1> according to the page they came from?

I have five unique forms each on a page of HTML. They then go to a PHP file to send the e-mail of data. Next they go to the HTML thank you page. I am hoping to change the heading according to which form they just submitted.
For example, if they submit a review, the should read "Thank you for your review" etc.
Technically all of these are saved as php files but only the e-mail page has php items.
Like <?php echo("<p>". $mail->getMessage()."</p>"); ?>
You should redirect to another php file and pass a parameter on url. Example:
sendemail.php
<?php
/** After send the email, check what kind form is (I don't know how do you check this).
This example is just to show you: */
if ($formType == 'review') {
$type = 'review';
} else if ($formType == 'anothertype') {
$type = 'anothertype';
}
header('Location: /thankspage.php?type=' . $type);
?>
thankspage.php
<?php
$type = $_GET['type'];
if ($type == 'review') {
echo '<h1>Thanks for your review</h1>';
} else if($type == 'anothertype') {
echo '<h1>Thanks for your anothertype</h1>';
}
?>
One way put a hidden field in your forms that'll get passed with the other form data. Then put an if statement on the thank you page and echo the appropriate message.
However, that'll only work either if you change the thank you page to php or change the page that receives and processes the form data to echo the thank you message as well

Php redirect to page if statement

I'm trying to make you redirect to the successful page after succesfully registering but whenever I click the register button I get redirected instantly even if all the input's are empty
if(isset($_POST["registration"])){
if(!empty($_POST["gender"])
and !empty($_POST["username"])
and !strlen($_POST["username"]) < 3
and !empty($_POST["email"])
and !email($_POST["email"])
and !empty($_POST["emailver"])
and !verification($_POST["email"],$_POST["emailver"])
and !empty($_POST["password"])
and !strlen($_POST["password"]) < 8
and strlen($_POST["password"]) < 25
and checkUppercase($_POST["password"])
and checkLowercase($_POST["password"])
and checkNumber($_POST["password"])
and !empty($_POST["passwordver"])
and !verification($_POST["password"],$_POST["passwordver"])){
if(addgamer($db,$_SESSION["gender"],$_SESSION["username"],$_SESSION["email"],$_POST["password"]) === TRUE){
$url = 'succesfull.html';
header($url);
}
}
}
The function for addgamers
function addgamer($db,$gender,$username,$email,$password){
$sql = "INSERT INTO gamers (`gender`, `username`, `email`, `password`) VALUES('$gender','$username','$email','$password')";
$db -> exec($sql);
if ($db->query($sql) === TRUE) {
$GamerId = $db -> lastInsertId();
$_SESSION['GamerId'] = $GamerId;
return true;
} else {
return false;
}
}
I found some answers here but all of them do the same and I have no solution for this.
GOTO($url);
Or
header('location: $url');
Or
if(addgamer($db,$_SESSION["gender"],$_SESSION["username"],$_SESSION["email"],$_SESSION["password"]) === FALSE ){
die();
}else{
$url = 'successful.php';
header($url);
}
Also tried with jQuery
echo "<script>window.location = '$url'</script>";
On every single click on the registration submit button you get redirected to the successful page but that should not happen until everything is filled in correctly as shown from the above code.
As you can also see I'd like to fix this problem trying with php only first.
Validate before submitting the form would be better at first.
As #Nicolas D mentioned you should also know that the form action is the page you direct to no matter what.
You can however set this to the current page by using action="" or action="<?php echo $_SERVER['PHP_SELF']; ?>"
This last could come with exploits, you can use "htmlentities($_SERVER['PHP_SELF'])" instead. Read about this here.
You have a missunderstanding PHP problem.
If your form use a submit form, it will post automatically to the php page targeted.
If you don't want to post to a new page and still verify your data, then you must use ajax in jquery : http://api.jquery.com/jquery.post/ . With that you ll catch your data without unexpected redirection.
Once all your form is validated by your php code during ajax call, you can redirect in jquery on the callback function.
Hope this will help, I ve been through this step and I remember it was painful

alert message won't display

I got a html page with 2 forms which are using the same php script..
<?php
if ($conn) {
if (isset($_POST['form_student'])) {
if ($_POST['form_student'] == 'Send') {
if (!empty($_POST["Ime"]) && !empty($_POST["Prezime"]) && !empty($_POST["BrojIndeksa"]) && !empty($_POST["TipNastave"])) {
header('Location: forme.html');
echo "<script>alert('Processing data to sql.');</script>";
} else {
echo 'You didnt fill all fields!';
echo "<script>alert('You didn't fill all fields!');</script>";
}
}
}
if (isset($_POST['form_subject'])) {
if ($_POST['form_subject'] == 'Send') {
// same checks just like above with redirecting
// and displaying alert box
}
}
}
?>
First problem is when I don't fill all fields in, it does work and echo 'You didn't fill al fields!' but doesn't display alert box message, and it only doesn't work when I don't fill all fields. And I'm wonder how can I actually by processing php script, without redirecting to that php script page, show msg box on html page, is it possible with out ajax or jquery, or I should instead using html extension change into php, and do all checks there and avoid processing script into action=""?
That's because of the row ..
echo "alert('You didn't fill all fields!');";
Try this one instead ..
echo "alert(\"You didn't fill all fields!\");";
What you did wrong was that you had an apostrophe in the string and around the string. I don't know how to explain this but I simply made the two quotation marks to not conflict with the php echo.
Update:
Regarding the second question about the redirect and such. Could you explain it further because I don't understand a word?

PHP : how to return back to previous page while closing pop up

I have a form submission. While i Click Submit button, will check for mandatory fields and if the fields are blank, I am opening a popup window using javascript to show error message. So once I close the popup I am not going back to previous page Instead it shows a white blank screen.
My code for verification and opening popup is :
<?php
if (isset($_POST['submit']))
{
if ($task == '' || $comments == '')
{
// generate error message
print "<script type='text/javascript'>";
print "window.open('error.php','new_window1','status=1,scrollbars=1,resizable=0,menu=no,width=320,height=220');";
print "</script>";
}
else
{
$sql3= "INSERT INTO work (task, comments, assignee, type, priority, dataum1, dataum2, status) VALUES ('$task', '$comments', '$assignee', '$type', '$priority', '$dataum1', '$dataum2', '$status')";
mysqli_query($mysqli,$sql3) or die(mysqli_error($mysqli));
}
}
?>
Since you are using a JS-popup you would probably want to do the mandatory-check client-side with JavaScript (keep the server-side check as well though), and then prevent the form from posting if the necessary fields aren't filled out.
Post the form data to the same page where you have the form. And add the above validation code to the top of that page. So when a validation error occurs, the user sees a popup with the error message, but he is on the same page where the form is.

Categories