Andreas Eriksson
Andreas Eriksson

Reputation: 9027

Search MySQL with PHP and display results on the same page

This is definately a novice question, but if you could be of any help i would be very grateful.

Basically, i'm building a database management page, and it of course includes a search function.

So, the search form looks something like this

<form name="name" function="search.php" method="get">

But, whenever i use it, i will of course get redirected to search.php. What i want is a way to display the results on the same page i did the search from (let's say index.php), without having to build an entire identical page around search.php

Thankful for answers.

Upvotes: 2

Views: 13197

Answers (2)

Andreas
Andreas

Reputation: 5335

Use a hidden field in the form that indicates that the form has been submitted.

In your form page (e.g. index.php)

<form name="name" action="index.php" method="post">
{OTHER_FORM_FIELDS}
<input type="hidden" name="doSearch" value="1">
</form>

So in your php code (could be in the index.php page or in a php script included)

<?php 
 if($_POST['doSearch']==1) {
 //query database
 //get results
 } ?>

in your index.php page

<?php if($_POST['doSearch']) { //a search request was made display my search results ?>
HTML_CODE
<?php } ?>

Upvotes: 3

Mark Byers
Mark Byers

Reputation: 838146

Let the page submit to itself:

<form name="name" function="index.php" method="get">

In the handler for the page, check whether or not you have parameters and display either the input box or the results as appropriate.

You could even take it one step futher. You could use AJAX to insert the results directly into the page content when the submit button is pressed, rather than causing a page refresh.

Upvotes: 3

Related Questions