Question

Good morning everyone,

I have a page that performs a default connection to database, search and looped output of data to the page by applying a template for each result in the table using this code:

<?php

$result = mysqli_query($con,"SELECT * FROM XXX WHERE Type='ABCD';");

while($row = mysqli_fetch_array($result))
{
    include('includes/template-1234.php');
}
mysqli_close($con);

?>

On the same page I have a simple HTML search box:

<div id="srch-form">
<form>
  <input name="srch-box" type="text" id="srch-box" size="45" onClick="this.value='';" onFocus="this.select()" onBlur="this.value=!this.value?'Enter Product Name or SKU#':this.value;" value="Enter Product Name or SKU#">
  <input type="submit" name="srch-btn" id="srch-btn" value="Search">
  </form>
</div>

Because I am just learning PHP - how do I set this up so that the default action still occurs on page entry, but - onsubmit of something in the searchbox the data in the current page is replaced by the results of the submission? I guess I'm getting confused over the fact that since I have already assigned a value(s) to $result to get the default output, If the value of $result is changed by the search form, does PHP automatically refresh the page when the value of $result is changed? - Sorry if this is a simple thing.

Was it helpful?

Solution

First, you'll have to add an action (which file to refer when submitted) and preferably a method-type in your form-tag. You will also have to include value of $productName (given from server-side php) inside of your html (look at value attribute)

Do something like this:

html-form: (Examplefile: yourhtmlform.php)

Then in your php-file get value from a specific element like this:

<?php
//File querydb.php (example filename)

//Form is submitted and srch-box is set (only set when form is submitted)
if(isset($_POST['srch-box'])) {
    $type = $_POST['srch-box']; //Get value of input-element 
}
else {
    $type = 'kingkong'; //Default type to search
}

$prepareQuery = mysqli_prepare($dbConnectionLink,"SELECT * FROM XXX WHERE Type=:type");
//...code to fetch results..
//You get a productName (or SKU) from db

if (isset($result['product_name'])) {
    $productName = $result['product_name']; //or whatever your column is called
}
else {
    $productName = '';
}

include('yourhtmlform.php'); //Observe that it must be php to echo out value of $productName in this included file

I noticed you didn't use prepared-statement. Look for more information on prepared statements here: http://www.php.net/manual/en/mysqli.prepare.php (use them!)

I hope this will help you somehow :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top