I can't seem to figure out how to return the result to the same page. When I get the result from the database it opens up a new page (search.php) but I want to stay on the same page as the form (the html page) I would greatly appreciate anyone that could be of help.

<html>
    <head>
        <title>FIND YOUR GID</title>
    </head>

    <body>

    <form action="search.php" method="post">
     Search: <input type="text" name="term" /><br />
    <input type="submit" name="submit" value="Submit" />
    </form>

    </body>
</html>

<script type="text/javascript">
var arrRequiredFields = [ "term" ];
window.onload = function() {
   document.forms[0].onsubmit = function() {
      for (var i = 0; i < arrRequiredFields.length; i++) {
         var field = document.forms[0].elements[arrRequiredFields[i]];
         if (field && field.value.length == 0) {
            alert("Missing Name of Food");
            field.focus();
            return false;
         }
      }
      return true;
   };
};
</script>

and this is the php

<?php
mysql_connect ("localhost", "","")  or die (mysql_error());
mysql_select_db ("");

$term = $_POST['term'];

$sql = mysql_query("SELECT * FROM `Find Your Gid` where Name like '%$term%'");
if (mysql_num_rows($sql) <= 0) {
// no results
echo 'No results found.';
} else 
if ($term ="") {
echo 'No name entered!';
} else
echo "<fieldset>"; 
while ($row = mysql_fetch_array($sql)){

    echo '<br/> Name: '.$row['Name'];
    echo '<br/> Gid: '.$row['Gid'];
    echo '<br/> Giftable: '.$row['Giftable'];
    echo '<br/><br/>';
    }
   echo "</fieldset>"; 

mysql_close();
?>

I read that I should try this: $_SERVER['PHP_SELF']; instead of search.php But its reading it as url and I get 404 error

Recommended Answers

All 14 Replies

The reason why you are opening a new page when you click on the submit button is because of your form action.

<form action="search.php" method="post">

You are sending the user to the search.php page. If you want the results on the same page, you'd have to post to the same page, read in the post values, do your DB lookup and display the results. If you want one page to do multiple things, you'll need some logic (if..else) in your code to determine what to display based on where the user is in the process.

You wont be able to post back to an HTML page, because you need server side coding. So your initial page needs to be a PHP page not HTML if you do intend on using one page.

Ok great thanks that helped. Another thing my php shows all thats on my database. so if i go to search.php you see all of it. How can I change that?

Adjust your SQL query. Your current statement is asking SQL to return all fields and only rows where the field called name has a value that matched your LIKE clause.

SELECT * FROM Find Your Gid where Name like '%$term%'

If you only want specific fields then specify them. For example.... SELECT field1, field2, etc. FROM tableName.

Also modify your where clause if its not returning the results you are looking for.

Its returning the correct info that I want. But when I changed the html file to php file which now includes the form and the php...the php is displaying all of my database info along with the form when first loaded. Is there a way to hide that?

Ok, i misunderstood...I see..yes on the first load, term has no value so since you are doing a LIKE in SQL, it brings back all rows.

I beleive the way you are going to approach this is to use an if..else block.

For example... if you detect that there has been no POST, show the form, dont show the results. If you detect that data has been posted, dont show the form, show the results instead.

PSEUDO Code..

if (POST term has no value...) {
  // Show form, no code for DB query here...
}
else {
  // term has value, only show DB results...
}

So I see that you are only passing values for 'term'. On the first load, this should not have any values. You can test for that.

I hope that helps.

thanks that looks like what I would need but not sure where to put it..

It seems no matter where I put that if statement I come up with errors. Obvioulsly doing something wrong.

Maybe, post your updated code. I'll be out for a while but can take a look as soon as I can. Otherwise, there are a lot of members of this site much smarter than I am on PHP...hopefully someone else will jump in with additional guidance.

Oh ok..thanks. I found a bit of a work around but would much rather do it the right way.

<html>
    <head>
        <title>FIND YOUR GID</title>
    </head>

    <body>

    <form action="findyourgid.php" method="post">
     Search: <input type="text" name="term" /><br />
    <input type="submit" name="submit" value="Submit" />
    </form>

    </body>
</html>

<script type="text/javascript">
var arrRequiredFields = [ "term" ];
window.onload = function() {
   document.forms[0].onsubmit = function() {
      for (var i = 0; i < arrRequiredFields.length; i++) {
         var field = document.forms[0].elements[arrRequiredFields[i]];
         if (field && field.value.length == 0) {
            alert("Missing Name of Food");
            field.focus();
            return false;
         }
      }
      return true;
   };
};
</script>




<?php
mysql_connect ("localhost", "","")  or die (mysql_error());
mysql_select_db ("");

$term = $_POST['term'];

$sql = mysql_query("SELECT * FROM `Find Your Gid` where Name like '%$term%'");

 if (mysql_num_rows($sql) <= 0) {
// no results
echo 'No results found.';
} else 
if ($term ="") {
echo 'No name entered!';
} else

echo "<fieldset>"; 
while ($row = mysql_fetch_array($sql)){

    echo '<br/> Name: '.$row['Name'];
    echo '<br/> Gid: '.$row['Gid'];
    echo '<br/> Giftable: '.$row['Giftable'];
    echo '<br/><br/>';
    }
   echo "</fieldset>"; 

 mysql_close();
?>
<?php
mysql_connect ("localhost", "","")  or die (mysql_error());
mysql_select_db ("");

if(isset($_POST['submit']) && !empty($_POST['submit'])){

    $result = ""; //USED LATER
    /*$term = $_POST['term']; THIS WORKS BUT FOR SECURITY ISSUES USE:*/
    $term = mysql_real_escape_string($_POST['term']);//AVOID MYSQL INJECTION

    $sql = mysql_query("SELECT * FROM `Find Your Gid` where Name like '%$term%'");

     if (mysql_num_rows($sql) <= 0) {
        // no results
        //echo 'No results found.'; BETTER ECHO LATER
        $error = "No result found";
    } else if ($term ="") {
        $error = "No name entered!";
    } else {
        $result .= "<fieldset>";
        while ($row = mysql_fetch_array($sql)){

            $result .= '<br/> Name: '.$row['Name'];
            $result .=  '<br/> Gid: '.$row['Gid'];
            $result .= '<br/> Giftable: '.$row['Giftable'];
            $reuslt .= '<br/><br/>';
            }
           $result .= "</fieldset>"; 
    }
     mysql_close();
}
?>


<html>
    <head>
        <title>FIND YOUR GID</title>
    </head>

    <body>

    <form action="findyourgid.php" method="post">
     Search: <input type="text" name="term" /><br />
    <input type="submit" name="submit" value="Submit" />
    </form>

    <div name="Results">
    <?php
    if(isset($error)){echo $error;}
    if(isset($result)){echo $result;}
    ?>
    </div>

    </body>
</html>

<script type="text/javascript">
var arrRequiredFields = [ "term" ];
window.onload = function() {
   document.forms[0].onsubmit = function() {
      for (var i = 0; i < arrRequiredFields.length; i++) {
         var field = document.forms[0].elements[arrRequiredFields[i]];
         if (field && field.value.length == 0) {
            alert("Missing Name of Food");
            field.focus();
            return false;
         }
      }
      return true;
   };
};
</script>

I didn't try this code but try to understand it and modify it to work as you want ...
Btw PHP code is almost every time inserted on the top of the page because you will use variable and results of the php process later in the display part which is the HTML ;)
And if you are wondering why I inserted this condition if(isset($_POST['submit'])), because by default when the page is loaded, it does not have 'submit' input passed to it unless you click it. Same thing for the other input inside the <form>.
Good Luck

Thanks very much works great!

Is there a way I could also get the result to show as a table rather than using fieldset? I tried before and I just came up with errors.

Displaying a table needs basic HTML knowledge. If you want to learn the basics go to: www.w3schools.com
Here's how you do it:

...

if(isset($_POST['submit']) && !empty($_POST['submit'])){

    $result = ""; //USED LATER
    /*$term = $_POST['term']; THIS WORKS BUT FOR SECURITY ISSUES USE:*/
    $term = mysql_real_escape_string($_POST['term']);//AVOID MYSQL INJECTION

    $sql = mysql_query("SELECT * FROM `Find Your Gid` where Name like '%$term%'");

     if (mysql_num_rows($sql) <= 0) {
        // no results
        //echo 'No results found.'; BETTER ECHO LATER
        $error = "No result found";
    } else if ($term ="") {
        $error = "No name entered!";
    } else {
        $result .= "<table>";
        $result .="<tr><td>Name</td><td>Gid</td><td>Giftable</td></tr>";
        while ($row = mysql_fetch_array($sql)){
            $result .= '<tr>';
            $result .= '<td>'.$row['Name'].'</td>';
            $result .= '<td>'.$row['Gid'].'</td>';
            $result .= '<td>'.$row['Giftable'].'</td>';
            $result .= '</tr>';
        }
        $result .= "</table>"; 
    }
     mysql_close();
}

...

Thanks again for you help..Really appreciate it..I'm still a newbie learning more and more everyday!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.