tags:

views:

134

answers:

2

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!

A: 

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.

Andy Moore
+1  A: 

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.

asgerhallas
a) use mysql_real_escape_string() in your answer. b) it won't work with the + for concatenation. you'll need dots. otherwise good example for actually doing it all on one page!
tharkun
Your right... It's a while since I've used PHP. I have editted to reflect your comments.
asgerhallas
Two more nitpicky things: mysql_fetch_row() doesn't return an associative array, mysql_fetch_assoc() or mysql_fetch_array() will do that. Also, those functions all take a MySQL resource as an argument. But otherwise, good answer.
htw