Reputation: 85
I am trying to create a Wordpress page which contains a Search form, but I can't display the search results on the same page. I've seen that I should include a Wordpress loop in my php file, but I can't figure out how.
Here is my search form:
<form id="searchform" action="../search4.php" method="post"><input id="Cref" style="height: 20px; width: 140px;" name="Cref" type="text" value="" />
<input id="submit" name="search" type="submit" value="Search" />
</form>
The search4.php file is this one:
<?php
$servername = "localhost";
$username='root';
$password = "";
$dbname = "mydb";
$mysqli = new mysqli($servername,$username, Null, $dbname);
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
if(! get_magic_quotes_gpc() ) {
$Cref = addslashes ($_POST['Cref']);
}else {
$Cref = $_POST['Cref'];
}
session_start();
$results="SELECT * FROM mytable WHERE CRF LIKE CONCAT ('%', $Cref, '%')";
$resultSet = $mysqli->query($results);
$numRows = $resultSet->num_rows;
if ($numRows > 0) {
while ($row = $resultSet->fetch_object()) {
echo "{$row->CRF} {$row->Name} {$row->Description} <br>";
}}
else
{
echo "No Results";}
?>
Upvotes: 2
Views: 4884
Reputation: 171
Here is what I did:
Custom form:
<form role="search" method="GET" id="searchform" action="<?php echo get_permalink(); ?>">
<input type="text" name="search" id="search" value="search">
<input type="submit" id="searchsubmit" value="Search" />
</form>
On the page I wanted the search results:
I did a WP_query
like on the codex
and changed the $args
to:
if( isset( $_REQUEST['search'] ) ){
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'paged' => $paged,
'posts_per_page' => 16, //or any number
'post_type' => 'post', //or your custom post type if needed
's' => $_REQUEST[ 'search' ]
);
}
Upvotes: 3