Php and forms problem - php

This is my super-simplified index.php:
<?php
require_once 'DeleteOrAdd.php'; // handles adding/deleting a db record
doAddDeleteRecord();
// other functions are called here, left out though for brevity
?>
Here's DeleteOrAdd.php (much simplified)
<?php
function doAddDeleteRecord()
{
echo <<<_END
<form action="index.php" method="post">
// the other form html not shown here
<input type="submit" value="ADD RECORD" />
</form>
_END;
// NOT SHOWN -- code to handle the form when it is POST'd
}
?>
So it's late 10:30pm, I'm new to PHP, okay /excuses.
Can't figure out how to do this.
I want to change my form action="index.php" above to form action="DeleteOrAdd.php"
(ie. I want to re-post to the same file that this form is in,
not to index.php, so the code is cleaner).
but it won't work because I have all the form-handling logic for the POST --
inside the doAddDeleteRecord() function, so if I set my form action="DeleteOrAdd.php"
it won't work.
Is it possible to do something like form action="DeleteOrAdd.php:doAddDeleteRecord()?
I don't want to put this in classes.
I also want to keep my index.php just as it is above -- calling functions and no major
inline code beyond that.
Any ideas?
Originally, all the code was inline inside index.php (got it from a PHP book's sample)
and I then divided the code into logically-named PHP files in the Netbeans project
to clean it up, and to put stuff in functions that get called from index.php.

remove the action value completly from the form, default it will post always back to the url on which it is displayed.
<form action="" method="POST">

Your application is not well structured. I would recommend to follow MVC pattern.
But for your current problem you can do something like this
just set the action to your <form action="DeleteOrAdd.php" or you can leave the action completely blank which post your data on the same file in which the form is created.
When the form is posted your could do below in your DeleteOrAdd.php file.
if (isset($_POST['submit']))
{
doAddDeleteRecord();// this will call your
}
but in this case you may have to change the code of your index.php

I think the problem you have here is being able to make your PHP page discern between whether or not its a fresh load or whether or not its submission of the form, and that is why your incorporating the index page in your action parameter. However, this is not necessary.
Set the id and name (for valid markup) attribute of your submit element to a unique name. Such as "form_submit" so here is an example.
<form action="" method="post">
<input type="submit" id="form_submit" name="form_submit" value="ADD RECORD" />
</form>
So what you put in your PHP script (doAddorDelete.php) is this ...
if (array_key_exists('form_submit', $_POST)) {
//this is the code to execute on form submit
//use print_r($_POST) to view variables you can use here
//make sure you validate all data passed here especially if using a database
//ie if MySQL
//$validated_userinput = mysql_real_escape_string(strip_tags(htmlentities(trim($_POST['userinput']))), $link_resource); for text
//(int) $_POST['userinput']; for numbers
} else {
echo <<<_END
<form action="" method="post">
// the other form html not shown here
<input type="submit" id="form_submit" name="form_submit" value="ADD RECORD" />
</form>
_END;
}
Hope this helps! :)

Foreword: Since you say this as a learning exercise, I'll skip past the sanctimonious manifesto on best practice and the many and sundry virtues of OOP. ;) Your book probably details every dire warning / stern lecture I'd normally prepend to a solution like this anyway.
Is it possible to do something like
form
action="DeleteOrAdd.php:doAddDeleteRecord()
?
In short, yes. The easiest way to accomplish your goal is to just reference your file in your form action, as you've done:
<!-- form.php -->
<form action="DeleteOrAdd.php" method="POST">
And then in DeleteOrAdd.php, trigger your function by testing the $_POST data your form submit will send in, like so:
<?php
// DeleteOrAdd.php
if(isset($_POST['some_form_variable']) && $_POST['some_form_variable'] != null) {
$data = array();
foreach($_POST as $post) {
array_push($data, $post);
}
doAddDeleteRecord($data);
}
function doAddDeleteRecord($data) {
// ...your processing code, etc.
The upshot to a purely procedural approach like you've specified is quite frankly, you can do stuff like this. You wouldn't want to develop like this in real life (skipping this deep-dive too, I guarantee your book explains why not in exhaustive detail.)
Important note!! Since I didn't see a return value in the code snippet you posted, and you say you're just getting started, I'm going to take a minute and point out a hidden pitfall here just in case:
--> Your code might work perfectly with those six lines I added above your function, and you'd never know it if you're not
returning a value (which proves the code ran, if nothing else) and
capturing said value so you can act on it / display it / otherwise show yourself that
a. something happened -- and ideally,
b. what that something was.
Otherwise, all you've got is ambiguity: no indication it's either working or breaking (not throwing errors, warnings, etc). Frustrating to debug, to say the least.
So, that stated -- presuming you've got your function returning something (true on success, string with a message, whatever) it probably goes something like this:
function doAddDeleteRecord($data) {
// ... your function code, etc.
$sql = "INSERT INTO mytable VALUES(".implode(',',$data).")";
if (mysql_query($sql) == true) {
$message = "Record saved";
} else {
$message = false;
}
return $message;
}
Any value your function returns needs a variable to capture it or it won't be set. Capture it with a variable assignment when you call your doAddDeleteRecord() function:
... // same 6 little lines of conditional code ...
}
$result = doAddDeleteRecord($data);
}
// maybe just echo it out or something...
echo $result;
-- or --
... // still the same 6 lines ...
}
$result = doAddDeleteRecord($data);
}
// maybe have a new test based on the outcome of the last one...
if ($result == false) {
// do something about the fail...
} elseif (is_string($result)) {
// do something about the success...
}
Good luck, HTH. :)

Related

How do i go about echoing back to a form from a form post action?

I have a form containing a textarea for inputing text into. The form also contains a submit button. After pressing the submit button it posts the text within the textarea into my php document. Within my php document the text is added to a database. Once it has been added to the database I would like it to echo back a response telling the user that it has added the text to the database successfully.
However, if i make it echo that response back to the home page, there is nowhere declared for it to display the echoed message. Has anyone got an idea of what i should be doing in order to get this working? Many Thanks.
Normally i wouldn't use a post straight from the form and i would use ajax and then display the data within a paragraph or something on it's return, however since the form is doing the post it's self i am not sure where to then declare where the response should show up.
The bellow displays my html form code and shows it's action to post to a php file.
<div id="userban2"><form id="bannable" action="/onlineusers.php" method="post"><p> Type username to ban bellow:</p>
<textarea name="banned" id="banned" maxlength="255"></textarea><br/>
<input type="submit" value="Send" class="extrabuttons" onclick="return false; preventDefault();">
<div id="cancelban" class="extrabuttons"><p> cancel</p></div>
</form>
However when in my php file i write ....
echo "the information has been added to the database successfully";
It might send the echo back however it isn't declared to display anywhere how can i change this to make it display the response within my form?
As requested return from my php
if(isset($_POST["banned"])){
$ban_name = $_POST["banned"];
bannedd($ban_name);
}
function bannedd($ban_name) {
$query1 = mysql_query("INSERT INTO banned_users (username,firstname,lastname,email,password,ip_address,sign_up_date,last_logged_in,about,sta rr,userpref) VALUES('$usernameb','$fnameb','$lnameb','$emailb','$passwordb','$ip_addressb','$sign_up_date b','$last_logged_inb','$aboutb','$starrb','$userprefb')") or die("Could not insert your informaion");
echo "This user has successfully been banned";
}
The form posts what is written in the form due to it having the action and method of post to my php. However should i then have any return i am not sure how i declare where the returned information should then show (The echoed message).
If I understand you correctly, your form is in some index.php file and sends the data to other file - onlineusers.php, and you want to display the message in the original page?
If this is the case, the most simple way I can think of is redirect back to the original page with a URL parameter, instead of echoing.
Do this at the end of onlineusers.php:
<?php
// insert text into DB ...
header("Location: index.php?result=ok");
?>
This redirects the browser back to the original page with the form. There you check if the status variable is set:
<html>
<head></head>
<body>
<?php if(isset($_GET["result"]) && $_GET["result"]=="ok") { ?>
<p>The information has been added to the database successfully</p>
<?php } ?>
<form> ... </form>
</body>
</html>
As you can probably see, you could set other results, such as "error" this way.
If you don't like the extra string in your URL, then create a cookie after processing the form in onlineusers.php and back at the original page, check if such cookie has been set. If you need more detail on that, let me know. And if you're asking something completely different, well, never mind :)
Your form is being submitted to /onlineusers.php
This is where you would want to add your echo statement.
If you require the info on the same page you technically return to the same page with the form action being $_SERVER['PHP_SELF'].
<form id="bannable" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Then you can put in a conditional statement prior to the load of your document, and include the PHP script.
<?php
$testVar = false;
$msg = '';
if($_POST) {
include '/onlineusers.php';
//... do something e.g post to database and return true.
}
if($testVar) {
$msg = 'Successful writing to DB!';
} ?>
<html>
<body>
<?php echo $msg; ?>
</body>
</html>
This will check to see if you have any post data, if you do, then it includes the script you specify. Maybe set $testVar to true if the writing to DB is successful, and then return $msg in your HTML.

Onblur or onchange check, using a php function in a registration form

I would like to be able to check the text in a text-box after it has changed, and report what is wrong.
It is for a registration form.
This is a part of register.php where
<form action"" method="post">
<ul class="ul-reg">
<li>
<p>Username: </p><input name="username-field" type="text" onblur="someFunction()" /><span id="UsernamehelpText"> </span>
</li>
</ul>
</form>
Then I would have a registerfunctions.php where i would store all the functions for checking lenght,char,maybe regex etc.. Its not really that important what functions i call. I just don't know how to call them.
Form what i have seen the span is where u post the errors, but if there is any other option im open for it, all i want is to be able to post the erorr text in the same line as the text-box
I have checked JavaScript and AJAX, but I am pretty new in this and don't really understand how it works.
After discussion in comments I understand what you want.
First, an explanation. There are two places where validation occurs: In your frontend (your web page) and in your backend (in the PHP script that saves the posted values). Anything that you really don't want to save - for example unescaped SQL strings, too-long fields, and so on - has to be validated in PHP, because it is trivial to get around Javascript validation. For example, nothing is stopping someone from sending a POST to your server containing illegal values without even bothering to visit your webpage.
Even though you need to perform validation in the back-end, it's still user friendly to do the same validation in the front end, so the user doesn't have to wait as long to see an error. This also reduces traffic to your server. Something you probably want to do in a big project is to have some kind of system for writing validation rules centrally, and then using those rules to dynamically generate both PHP and Javascript validation. The advantage of doing that is that you don't duplicate your business rules in two places, but in a smaller project it's probably not worth the hassle.
Validation in the frontend looks about like this: You bind an event handler to an appropriate event or events (you can add onkeydown="validateUserName()" for example, so that the validation reacts a bit quicker), and update your warning text appropriately.
<form action="" method="post">
<ul class="ul-reg">
<li>
<p>Username: </p>
<input id="username" name="username-field" type="text" onblur="validateUserName()" />
<span id="UsernamehelpText"></span>
</li>
</ul>
</form>
<script type="text/javascript">
function validateUserName() {
var userNameElement = document.getElementById('username');
//Do your work: Get the value of the user name field, check
// the values against your validation rules...
var helpText = document.getElementById('UsernamehelpText');
if(isValid)
helpText.innerHTML = "";
else
helpText.innerHTML = "Invalid!";
}
</script>
In the backend, when you process the form, you then have to check the same rules in PHP to prevent illegal values from being posted either maliciously or due to an error in your Javascript. If an error is found, you don't save, instead you can just re-render the form with the submitted values in the input fields and a message indicating what was invalid - this allows the user to change their inputs without losing the values they submitted.
With jQuery it would look something like this:
function someFunction() {
$.ajax({
url: "checkStuff.php",
data: $("input[name='username-field']").serialize,
success: function(data) {
if (data == "correct") {
$("#UsernamehelpText").html("Valid");
} else {
$("#UsernamehelpText").html("Invalid");
}
}
});
}
Your PHP could be something very simple that just checks the validity of the input and then echos "correct" if it is.

PHP Using both client side and server side validation WITHOUT using 3rd party code

EDIT: thanks for all the help. Received an email saying that we didn't need the client side so I scrapped that idea in favor of actually completing the assignment on time.
Before you ask, Yes this is assignment work. No I am not looking for someones complete code. I am a beginner will practically no experience in HTML/PHP/javascript, but this is the second part of the assignment so I already have some of my own code from the first part, which was so very easy in comparison to this part. The task doesn't specifically say we have to use client side validation, but I feel it would be good practice.
I need someone to clearly show me how to use both client and server side validation. I already have the javascript validation, but I can modify it as it displays an alert box for every error. I CANNOT use 3rd party code like jQuery which apparently everyone on the internet likes to use, and the course I am doing doesn't like to actually teach us any useful content so we are all on our own.
The data from the form will then be entered into a database through MySQL (which I am not looking forward to doing), and from viewing the minimal information from w3schools on the topic, I understand that I have to POST the form to itself.
The form itself is pretty simple: contains name, DoB, email, postcode etc.
My current .js uses alpha only, num only, date format, email format, radio button and check box checks and every field is tested to make sure it isn't empty.
I suppose what I am after is a complete tutorial on how to do this. My internet searches have been unfruitful, but at least I still have a week till this is due.
Any help is appreciated, but simple and clear help would be even more so. I will continue to prowl the internet for help until then and post back here if I find useful stuff for anyone else with the same problem (which I'm sure is 90% of my class.....)
Thanks in advance.
Read the code below. Hope inline comments answer your question.
add_record.php
<?php
if(isset($_POST['name'])) {
//get post data
$name = trim($_POST['person_name']);
$email = trim($_POST['email']);
$message = trim($_POST['message']);
//This is server-side check!
if (strlen($name) > 10){
echo "FAILED! You tried to submit a name which is greater than 10 chars."
}else{
//insert to the database here..
//and send out a "success message or render HTML
echo "SUCCESS!";
}
}else {
echo "Error! Proper parameters were not provided!";
}
a.html
<html>
<head>
<script type="text/javascript">
function checkForm(){
//client side (JS) validation. This happens before submitting.
var name = document.forms[0].person_name.value;
if (name.length > 10){
alert("Name is too long");
return false;
}
//do some more checks here..
//return true if all checks have passed, false otherwise.
//the return value of this function is checked before submit. The form is submitted only when this function returns a true.
return true;
}
</script>
</head>
<body>
<form action="add_record.php" method="POST" onsubmit="return checkForm()">
Name: <input type="text" name="person_name"/>
Email: <input type="text" name="email"/>
Message: <input type="text" name="message"/>
<input type="submit"/>
</form>
</body>
</html>
EDIT: As mplungjan pointed out, it is not a good idea to have a field named "name" inside forms. The form object itself might have a "name" which might conflict.
Since it's homework, I should at least point you to a few resources:
Client side
For validation:
http://www.9lessons.info/2009/03/perfect-javascript-form-validation.html (form validator)
http://www.javascriptkit.com/javatutors/re.shtml (regular expression guide)
Don't jump to AJAX straight away, that's advanced material. Get the basics done first and just let the form submit to PHP (i.e. page refreshes and PHP redraws the form if there were any validation issues).
Server side
For validation: http://www.php.net/filter - examples
For database work: http://www.php.net/pdo - tutorial
For server side validation, you would send the form data to a php page using method="post", then check for correct format. Something like:
<form action="validate.php" method="post">
<!-- form fields -->
</form>
In validate.php, you use $_POST["var_name"], where var_name is the name of your input fields, to check the data. So, for example, something like:
$age = $_POST["age"];
if (ctype_digit($age) && $age > 0) {
// correct format
}
It seems like you already have client side validation figured out. I'm not quite sure if I understood your problem correctly, though - Let me know where specifically you are having problems and I'll try to help.

Is it better to implement a FORM and its ACTION with a single PHP file or two files?

I'm creating a FORM with PHP for an intranet webpage. Another PHP script is called by submitting the form.
Before anyone asks, the form does not allow any uploads, and although the values entered in the form find their way into an SQL query, I strip out everything but numbers.
I'm wondering if there would be a advantage in using the same PHP file for both the FORM and the ACTION?
Obviously, increased complexity is the penalty — ie, figuring out, when invoked, if the FORM is to be created, or if the SUBMIT button has been clicked — but what would be the benefits?
EDIT: Note, the PHP in 'submit' mode does not redisplay the form, it does something entirely different. This is the source of the complexity I was worried about.
The form is used to enter values which are checked against values in a DB, but there are no changes made to the DB.
I tend to find it more maintainable to have the php that creates the form separate from the php that is called by the form.
It will also reduce (though it isn't noticeable) one if statement to determine if this is a form request or filling in the form.
But, the problem is that unless you are going to take them to a new page, you will have to get the values back into the form which can be more complicated.
So, if you want to keep the values in the form, even after the form is processed, then leave the form processing logic at the beginning of the file, otherwise I would opt for maintainability and have them in two files.
In most case, I prefer that.
Keeping both together make the code more 'cohesive' as the code of accepting value (via form) is in the same php file (called it View and Control). To me this is an advantage.
However, the code that manipulate database should be separated in other file as it not the same as accepting value (called it a model library). This make it less-coupling as accepting and manipulation is separated. This decoupling will reduce the complexity you are worrying about.
Another advantage of is the URL. The users will see it as from the same page.
However, this is totally depends on your overall system metaphor and work flow. For example, it make better sense to the users that addBook.php handle book adding form and show that the adding has success or fail. Comparing that too having two addBook.php, addBookProcess.php.
What I am trying to say is that the flow of pages should be a more important factor to determine if you want to separate or combine them. Decoupling interface/logic code will helps you reduce the complexity if pages need to be combine into one php file.
Just my though.
Form is about user interface, action is about doing something with data.
The part of code that actually processes user input must certainly be separate from the form structure.
The form code must accept default values (or values previously entered and found to be invalid), error messages etc. It must have nothing to do with usage of successfully submitted form data.
If you allow user to change invalidated input, then you must have action URL the same as form.
If successful submission leads to something unrelated, then its URL must be different from that of the form. Basically, you must redirect user from the URL where the form got accepted to the next URL.
If you're doing AJAX, none of this applies.
It depends!
The upside to having them in one file is that it puts a single block of functionality into one place and allows you to handle form validation. The downside is increased complexity. It really starts to suck if you have the markup for both pages in one file.
I would suggest having 3 files - the main PHP handler, the template for the form and the template for the result page. The main PHP file would look something like this:
<?php
$error_message = "";
if ($form_submitted){
if ($form_validated){
include("inc-result.txt");
exit;
}else{
$error_message = "something went wrong!";
}
}
include("inc-form.txt");
?>
if validation fails, the logic drops you back to the form, where you can display the previously entered values, along with the relevant error message.
it does depend but in the long-term I would suggest separation of forms and business logic.
For quick projects I do understand the short-term gain of keeping it in the same page but you never know when the form you did needs to be added with features or needs to be turned to an ajax form. If you keep your logic separate from the form you would be ready for these changes quicker.
Well, mainly if you want to re-show the form to the users without losing data, then you can just write something like this:
<input type="text" name="myInput" value="<?php
echo htmlspecialchars(isset($_POST["myInput"]) ? $_POST["myInput"] : "");
?>">
Update: here is an example of this method:
<?php
$error = "";
$result = "";
$a = isset($_POST["a"]) ? $_POST["a"] : "";
$b = isset($_POST["b"]) ? $_POST["b"] : "";
if ($a !== "" && $b !== ""){
if (is_numeric($a) && is_numeric($b))
$result = sprintf("%s + %s = %s", $a, $b, $a + $b);
else
$error = "You must enter two numbers!";
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head><title>Sum numbers</title></head>
<body><form method="post" action="<?php print htmlentities($_SERVER["REQUEST_URI"]); ?>">
<p><strong>Enter two numbers to add them together.</strong></p>
<?php if ($error){ printf ("<p><em>%s</em></p>", htmlspecialchars($error)); } ?>
<p>
<input type="text" name="a" value="<?php print htmlspecialchars($a); ?>">
+
<input type="text" name="b" value="<?php print htmlspecialchars($b); ?>">
<input type="submit">
</p>
<?php if ($result){ printf("<p><strong>%s</strong></p>", htmlspecialchars($result)); } ?>
</form></body>
</html>
It seems like you should do 2 things:
1) create controller that steps in to see if you are doing an edit action or a display action
you already have the start of one at the top of your file there, just make it include "form.php" (your form) after it does it's business. So yes, make 2 files.
2) pull all that crappy formatting code up into the controller. Calculate all your values before the form is ever loaded. This includes running htmlspecialchars on all your form elements that need it. You can even loop through them to save lines of code:
i.e.
$cleanTheseVars = array ($a, $b, $c $error, $result);
array_walk($cleanTheseVars, 'htmlspecialchars' );

PHP Query from a FORM

So I have a form that I post to a page and in the form I'm posting certain variables that I build one of my queries with and then call them on my page. How can I post data and also build a query and display the answer on one call?
Maybe I'm not wording it right and I'm learning this stuff, but I just don't know. Should I post to an intermediate page first?
Example: form (variables A & B) to-> page (A & B used in query) and then result is on that same page.
can this be done and what's the method?
Thanks!
This is the basic priniciple, but you must sanitize you input data from the form. For example using mysql_real_escape_string().
But in a single page you can have code like this (it is not tested, I'm not able to on this computer):
<?php
if(isset($_POST['name']))
{
$query = "SELECT * FROM table WHERE firstname = '"+ mysql_real_escape_string($_POST['name']) +"'";
while($node = mysql_fetch_rows())
{
echo "The result: " . $node['id'];
}
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name" />
</form>
This will post to it self, run the query and echo the result, and show the form again.
For small tools and the like, this is an ok approach, but for larger websites I would recommend not mixing the request handling code with the html. Look into using a framework for applying the mvc pattern or something like that.
Without specific examples it's hard to write it, but it's fairly simple.
In a very basic way:
File1.php:
--your form submits to file2.php--
File2.php:
function processForm(inputs) [
--MySql query goes here--
]
function displayResults() [
--Process your query results--
]
processForm($_POST['vars']...);
displayResults();
Does that make sense? Simply make a function that processes and then displays the results again.
If you want to get really fancy you can even do it all in a single file, but you should probably master this technique first if you are first learning.

Categories