Search MySQL with PHP and display results on the same page

12,914

Solution 1

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 } ?>

Solution 2

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.

Share:
12,914
Andreas Eriksson
Author by

Andreas Eriksson

Updated on June 13, 2022

Comments

  • Andreas Eriksson
    Andreas Eriksson almost 2 years

    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.

  • Andreas
    Andreas about 14 years
    If you are Using GET as the form METHOD then REPLACE $_POST with $_GET