Post and Get on the same page???

Let me first describe the code below. When you go to this page there is a text box to search for a word in two columns of a material table and a checkbox to put wildcards on both sides of that word. When you submit the form it returns a table with the results.

Question 1 - This is my first PHP page after using ASP classic for a while so I am learning. The code below works (minus any validation rules or string escaping). Does if look right? Am I going in the right direction?

Question 2 - I want the results in the material and description columns that are displayed in the table to be linked so that when you click on them it opens this page back up using the link as the new search criteria. I know I am getting the value from the textbox to build the query $search = $_POST["txtMaterial"]; when I make my first search. After I have my first set of results how could I setup the page to link back to itself and build the query using what I assume would be a $_GET?

Is that too confusing?

<div class="container">

//Connection string

<form action="" method="post">
<label>Material: </label><input name="txtMaterial" type="text" />
<input name="checkbox" type="checkbox" value="checked" /><label>Use Wildcards </label>
<input type="submit" name="submit" value="Search for Material">


if (isset($_POST['submit'])) { //Begining of IF statement for determining if text box has any data

//Query and connect
if (isset($_POST["checkbox"])) {
	$cbxval = "%";
} else {
$cbxval = "";}

$search = $_POST["txtMaterial"];

$query = "SELECT Description, Material, Job, Pick_Buy_Indicator ";
$query .= "FROM dbo.Material_Req ";
$query .= "WHERE(Description LIKE '" . $cbxval . $search . $cbxval . "') OR (Material LIKE '" . $cbxval . $search . $cbxval . "')";

$results = sqlsrv_query($conn, $query);?>

<table  class='table table-bordered table-condensed table-striped'>

<td><strong>Job No.</strong></td>

//Loop through array and display results in table
while ($row = sqlsrv_fetch_array($results)){?>
<td><?php echo $row['Job']?></td>
<td><?php echo $row['Pick_Buy_Indicator']?></td>
<td><?php echo $row['Material']?></td>
<td><?php echo $row['Description']?></td>
<?php }?>

//Free the results
sqlsrv_free_stmt($results);} //End of IF statement for determining if text box has any data?>


Open in new window

Robert FrancisDirector of Continuous ImprovementAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
I think I understand the question - you want to be able to process data as either a $_GET or a $_POST?

Without endorsing the method you are using (have not had a chance to look at it closely)

Have you had a look at the $_REQUEST array it will contain both $_GET and $_POST values.
$txtMaterial = $_REQUEST['txtMaterial'];

Open in new window

Failing that you could do something like this

$txtMaterial = isset($_POST['txtMaterial']) 
  ? $_POST['txtMaterial'] 
  : isset($_GET['txtMaterial']) 
      ? $_GET['txtMaterial'] 
      : '';

Open in new window

As to whether your code is right

1. Does it do what you want to?
2. Is it easy to modify should the requirement change?
3. Is it secure (does it filter out malicious input)?
4. Does it correctly trap errors and deal with them in a way that does not leave the page in a broken or indeterminate state?

Those are the questions you should be asking about the code - if the answer is Yes to all of them then you are on the right track.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ray PaseurCommented:
GET and POST method requests are typically used for different things.  GET requests must be nullipotent and idempotent.  POST requests must be idempotent, and may change the state of the resource (data set on the server).  The appropriate request for any kind of a search is GET, since it does not change the server.  With a GET request you can add a bookmark, send a link to  a colleague, get your web pages indexed by a search engine, etc., because the entire request can be captured in a URL.

I can't quite follow the intent of the script, but I think I can show you a design pattern that might work.  Give me a little while to prepare an example.  Hopefully it will lead you in the right direction.
Franck GaspozSoftware Architect, Technical ExpertCommented:
I think your code is serving correctly your needs, and will achieve your goals without using some heavy and long time to learn frameworks. However, try consider to use php and javascript frameworks in the future, that will help you to build more complex applications ( for instance symphony or zend framework ).
Secondly, you can build a get link for columns you mentionned, like this :
<td><a href="thepage.html?arg=<?php echo urlencode( $row['Material'] )?>"><?php echo $row['Material']?></a></td>
and thus you have to handle any get request on top of your script :
if (isset($_GET['arg']))  ...
and refiine your query consequently.
you could also call a javascript function from the href attribute of the link which can so initialize hidden fields of the forms and submit the form (by the way: document.forms["myform"].submit(); )
so you will only have to treat post queries.
Of course using jquery would greatly simplify all of this

does those ideas helps you a bit ?
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

Dave BaldwinFixer of ProblemsCommented:
I don't see any use for a GET in your code.  The query results come from the form data each time and that's just POST.
NerdsOfTechTechnology ScientistCommented:
A solution to both questions is to make the form action use GET and submit to itself (setup initial page code which will look for the GET value; if found it outputs the table)

The table can link by way of another handling php page that serves the matched document or you can recursively use the results of the first search, etc.,  the sky's the limit.

One critical warning is that since you are using LIKE make sure to use even stricter filtering than mysqli_real_escape_string as is DOES NOT remove an injected % nor_ which have special meanings in LIKE clauses. Therefore, a strong string filter which also removes % and_ is highly recommended.
greetings princeservice, ,  I am inclined to think from your question statements that this code -
     <td><?php echo $row['Material']?></td>
     <td><?php echo $row['Description']?></td>

would result in a page HTML as somethink like -
    <td><a href="">Hob ONE Material</a></td>
    <td><a href="">Hob ONE is great stuFF!</a></td>

where the page user can click one of the many links in table, to see more info about the product material or description?

You certainly can use both Get and Post data sends to the same PHP page, but You MUST make sure in your code work to have a definite SEPARATION, in the first test for if it's a GET or POST send, I would recommend a different post and get designations, so in your own head (thinking) you do not get the two mixed up as you might if you use a single designation.

Also you really really need to study up on database SELECT SQL and mysql injection PREVENTION, as you have this -

$search = $_POST["txtMaterial"];
$query .= "WHERE(Description LIKE '" . $cbxval . $search . $cbxval . "')

without Any attempt at SQL injection protection
Robert FrancisDirector of Continuous ImprovementAuthor Commented:
Sorry for the delay in a response. Just got back into town. I will review everyones responses soon. Thanks
Ray PaseurCommented:
Here's a general design for a search that uses a GET-method request.  There is no reason for POST when you're searching a data model.  Try searching for "Dave" and "R" to see it in action.  Obviously it's a simulation, but hopefully it will show the main points related to sanitize input, match to data model, report results.
<?php // demo/temp_princeservice.php
 * See
 * Demonstrate how to use GET requests to search a data model

$model = array
( [ 'name' => 'Richard Quadling' ]
, [ 'name' => 'Dave Baldwin' ]
, [ 'name' => 'Ray Paseur' ]

= !empty($_GET['q'])
? trim(preg_replace('/[^A-Z ]/i', NULL, $_GET['q']))

$out = NULL;
if ($q)
    foreach ($model as $row)
        if (strpos($row['name'], $q) !== FALSE)
            $out .= PHP_EOL . '<br>' . $row['name'];

if ($out) echo $out;

$form = <<<EOD
<label>Search for: </label><input name="q" value="$q" />
<input type="submit" value="Search" />
echo $form;

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.