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.
Related
Im trying to create a grid on my page in each cell there will be a simple one line form. If a person enters data into lets say FieldA I would like the php to perform actionA but if the data was entered in FieldF I would like actionF performed. Is this possible without having to create a php for each cell and upload all those php files?
Or is there a way to perform the GET method in each form to append the data to the end of the action url without the field name showing (ie sample.com/somestuff/fieldA instead of sample.com/somestuff/fieldname=fieldA) thus not needing php at all?
Did you try anything. Please try to write some code. If you get struck paste the code here, somebody will help you out..
In my opinion, why you need different forms. Just have a form which has n text boxes and perform the task that you need.
Your problem is a little ambiguous to me. I'll give it a shot though.
On the form I would set:
`method="post" action="<?php echo $PHP_SELF ?>"`
This will cause the form to submit back to itself. Then at the top of the page you could do something like the following:
<?php
if (isset($_POST["fieldA"]){
performActionA();
} else if (isset($_POST["fieldB"]){
performActionB();
}
etc...
?>
Is that what you are trying to do? Keep in mind php is executed server side before any interaction with the user.
otherwise you could use javascript to change the action field of the form. (Untested)
<script type="text/javascript">
function setAction(elt){
var page = document.getElementById(elt).value;
document.myform.action="sample.com/somestuff/"+page;
}
</script>
<form id="myform" action="sample.com/somestuff/">
<input type="text" name="text1" onchange="setAction('text1')" />
</form>
SAME PAGE RESULTS: (xmain.php)
//FORM (working good)
<form name="search" action="xmain.php" method="post">
code,code,code,
// QUERY (working good)
code,code,code,
<input type="submit" name="doSearch" value="doSearch">
//These are last 2 lines of my 15 line query - I have skipped the rest to save space:
$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM $tableName $qryWhere LIMIT $start, $limit;";
$result = mysql_query($sql);
// Table query results here.....
OK, although all code is working correctly ( Form is submitting variables, database results are correct, etc, there are 2 nagging problems:
1 - ALL database results are echoed when the page is first loaded. The page is refreshing from top to bottom without a stop in between - I would like for NO RECORDS to be shown at first page arrival.
2. Also, because of the top to bottom nature of this page,my option choices are being reset upon form submission. I would like to maintain selections until the RESET button -
that I have on the page for that purpose is clicked.
I realize that the form by always refreshing upon itself, is causing the above problems.
Any suggestions would be greatly appreciated! - see working sample here:
http://www.symbioticmusicpublishing.com/database3/xmain.php
Only show something when something is actually posted, so surround with if(isset($_POST['doSearch']){.. or something.
echo a value <input .... value="'.(isset($_POST['thisinputname'])?htmlspecialchars($_POST['thisinputname']:'')">
On more elaborate forms a session could be handy, not needed for simpler ones/forms always getting the post though. BTW, I prefer using GETs for listing data, makes it easier to share/link. POSTs for alterations, GETs for retrieving (and a few other methods for real REST).
Echo the retrieved values inside a if statement like Wrikken suggested. Check that your form submission button is actually clicked and only then echo the results.
If you're unfamiliar with the syntax take a look at ternary operator.
http://www.php.net/manual/en/language.operators.comparison.php
Also use GET if you are getting data from database. And POST when you are putting data into database. I guess the reason why goes beyond the naming convention but still it's a nice reminder: GET for getting and POST for posting/putting.
UPDATE
Sorry I didn't think this one through. Put the sql query inside a if statement. Put also the echoing of results inside a if statement.
if (isset[$_POST['doSearch']]){
//make the query
}
if ($sql){
//echo the results
}
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. :)
I've never really thought about this, but it helps with some security of something I'm currently working on. Is it possible to submit GET data without an actual input field, and instead just getting it from the URL?
If so, how would I go about doing this? It kind of makes sense that it should be possible, but at the same time it makes no sense at all.
Perhaps I've been awake too long and need some rest. But I'd like to finish this project a bit more first, so any help you can offer would be appreciated. Thanks
Yes. If you add some query-string to yourl url, you can obtain that in php using $_GET without form submitting.
Going to this URL adress http://yoururl/test.php?foo=bar cause echoing foo (if there will be no foo query string, you'll get warning).
# test.php
echo $_GET['foo'] # => bar
Is this what you mean?
Link
// page.php
echo $_GET['type']; // foobar
This is what I understand of your question:
You have a <form method="get" action="foo.php">-like tag on your page
You have a series of <input type="text" name="bar"/> in your page
You want to pass additional GET parameters that are not based on an input from the form
If so, it is possible, but I hardly see how it could help with security. Input from a client cannot be trusted, so even if you hardcode the GET value, you have to check it serverside against SQL injection, HTML injection/XSS, and whatnot.
You have two ways:
Use a hidden input: <input type="hidden" name="myHiddenGetValue" value="foobar"/>
Add the GET parameter to the form action: <form method="get" action="foo.php?myHardcodedGetValue=foobar">
If what you meant is that you want to have a GET request without a form, you just need to pass all the GET parameters to the href of a link:
Click here!
Yes it's possible. Just append the GET data to the link.
For example:
<a href="main.htm?testGet=1&pageNo=54>Test</a>
You can also use Javascript to build the url.
If you happen to be using jQuery and want to build the GET data dynamically you can do this:
var getParams = { testGet:1, pageNo:54 };
$(".myLink").attr("href", url + "?" + $.param(getParams));
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' );