简体   繁体   中英

php search form using post variable to make an sql query

this is a page that displays a list of creatives, and the form offers search functionality to search by job title:

 if(isset($_POST['creatives-submit'])){
    $job = $_POST['job-title'];
    $data = \Db::Common($fms5->DBH)->getWhere("creatives", "creatives_active", "Yes"," AND creatives_job LIKE '%".$job."%'")->orderBy('creatives_name', 'asc');
}

 <form method="post" name="creative-search"> <input class="form-control" type="textbox" name="job-title" id="job-title" placeholder="Search by job title" /> <input class="form-control" type="submit" name="creatives-submit" id="creatives-submit" style="display: none;" /> </form>

is there anything that's obviously wrong my my code?

try changing if(isset($_POST['creatives-submit'])) to if(isset($_POST['job-title']) && !empty($_POST["job-title"])) as the form is posting the job-title value and this is the value you actually care about. (Since creatives-submit will always = Submit )

also change <input class="form-control" type="textbox" name="job-title" id="job-title" placeholder="Search by job title" />

to <input class="form-control" type="text" name="job-title" id="job-title" placeholder="Search by job title" required/>

this means the form can't be submitted unless the job-title field has a value and had the correct type of text

Below is a modification of your code that just returns what the user searched for (Since I don't have it connected to a database)

<?php
 if(isset($_POST['job-title']) && !empty($_POST["job-title"])){
    $job = $_POST['job-title'];
    ?>
    <p>You Searched For <?php echo $job;?></p>
<?php   
}
?>

And the form

<!-- Search Form -->
<form method="post" name="creative-search">
    <input class="form-control" required="required" type="text" name="job-title" id="job-title" placeholder="Search by job title" />
    <input class="form-control" type="submit" name="creatives-submit" id="creatives-submit" style="display: none;" />
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM