Doing a simple PHP/SQL search bar on my database and the results aren't appearing. The search bar appears, and whatever i type isn't appearing in the URL. Code is below. I'm connecting to a database through a different file.
Index.php
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<center>
<form action="search.php" method="post">
<input type="text" name="search" autocomplete="off">
<input type="submit" value="search">
</form>
</center>
</body>
</html>
search.php
<?php
$search = $_GET['search'];
require 'constants.php';
?>
<?php
$query = "SELECT Name, Zip, Address, Type FROM parks WHERE Zip = '%{$search}%'";
$result = mysqli_query($db_connection,$query);
while ($row = mysqli_fetch_array($result))
{
// loop through output one row at a time
$name = $row["Name"];
$zip = $row["Zip"];
$address = $row["Address";
$type = $row["Type"];
echo $name . $zip . $address . $type;
}
?>
First off, you explicitly set the method type as POST:
<form action="search.php" method="post">
then, you're trying to get values of:
<input type="text" name="search" autocomplete="off">
Thru $search = $_GET['search'];. Use $_POST['search'];
Second, this doesn't make sense
WHERE Zip = '%{$search}%'";
If you want to search with a wildcard, better use LIKE clause.
And why not use prepared statements:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
if(isset($_POST['search'])) {
require 'constants.php';
$search = '%' . $_POST['search'] . '%';
$query = "SELECT Name, Zip, Address, Type FROM parks WHERE Zip LIKE ?";
$select = $db_connection->prepare($query);
$select->bind_param('s', $search);
$select->execute();
$select->store_result();
if($select->num_rows > 0) {
$select->bind_result($name, $zip, $address, $type);
while($select->fetch()) {
// loop through output one row at a time
echo $name . $zip . $address . $type . '<br/>';
}
}
}
?>
Another way of fetching:
if(isset($_POST['search'])) {
require 'constants.php';
$search = '%' . $_POST['search'] . '%';
$query = "SELECT Name, Zip, Address, Type FROM parks WHERE Zip LIKE ?";
$select = $db_connection->prepare($query);
$select->bind_param('s', $search);
$select->execute();
$results = $select->get_result();
if($select->num_rows > 0) {
while($row = mysqli_fetch_assoc($results)) {
// loop through output one row at a time
$name = $row["Name"];
$zip = $row["Zip"];
$address = $row["Address"];
$type = $row["Type"];
echo $name . $zip . $address . $type . '<br/>';
}
}
}
Related
Here is the code :-
<?php
include 'include/header.php';
include 'include/connect.php';
mysql_select_db("search_db") or die("Couldn't select database.");
$output = '';
//collect
if(isset($_POST['search']) && $_POST['search'] != "") {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM people WHERE name LIKE '%".
$searchq . "%' OR id LIKE '" . $searchq . "';");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'There was no search results!';
} else {
while ($row = mysql_fetch_array($query)) {
$fname = $row ['name'];
$id = $row ['id'];
$output .= '<div>'.$name.' '.$id.'</div>';
}
}
}
?>
<!--html-->
<form action="search.php" method="post">
<input type="text" name="search" placeholder="Search..">
<input type="submit"value="search">
I am trying to set up search in my website using php and mysql I am getting an error like this " An error has occurred - could not connect to the database."
Let me know search result code like name , user photo, description, type box anyone can help us appreciated
I'm trying to create a search bar for my website on my local server, but when I submit the page generated is just blank. I've been following a couple of guides online but can't seem to figure out why it is not connecting to my MySQL db and getting the results. This is my first time attempting db and PHP so appreciate all advice.
<form action="./search.php" method="get">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
Search.php
<?php
$conn = mysqli_connect("localhost", "root", "root", "womendig_search");
if(mysqli_connect_errno()){
echo "Failed to connect: " . mysqli_connect_error();
}
error_reporting(0);
$output = '';
if(isset($_GET['q']) && $_GET['q'] !== ' '){
$searchq = $_GET['q'];
$q = mysqli_query($conn, "SELECT * FROM search WHERE keywords LIKE '%$searchq%' OR title LIKE '%$searchq%'") or die(mysqli_error());
$c = mysqli_num_rows($q);
if($c == 0){
$output = 'No search results for <b>"' . $searchq . '"</b>';
} else {
while($row = mysqli_fetch_array($q)){
$id = $row['id'];
$city = $row['city'];
$country = $row['country'];
$descriptions = $row['descriptions'];
$output .= '<h3>' . $title . '</h3>
<p>' . $desc . '</p>
';
}
}
} else {
header("location: ./");
}
print("$output");
mysqli_close($conn);
?>
The $title and $desc were not defined so you have empty <h3> and empty <p> tags.
Also i think it's better to make a few changes in your code.
Use !empty($_GET['q']) instead of $_GET['q'] !== ' ' and use extract($row); instead of
$id = $row['id'];
$city = $row['city'];
$country = $row['country'];
$descriptions = $row['descriptions'];
I been trying to implement PDO with prepare(), bindParam() and execute() functions to allow a query to be constructed from data entered by the user.
I wanted to display the list of books and then allow the user to filter the list and then see the new list and the full list.
When I enter criteria into the form to search nothing happens. What am I overlooking?
here is the code
<?php
$pageTitle = "Book List";
$pageHeading = "Book List";
include_once ('header.php');
include_once('databaseConnection.php');
if(isset($_POST['txtSearchBookTitle'])) {
$db = new DatabaseConnection();
$db = $db->db_connection;
$searchTitle = ($_POST['txtSearchBookTitle']);
$sql = $db->prepare("SELECT title FROM tblBook WHERE title LIKE ('%:searchTitle%') ORDER BY title");
$sql->bindParam(':searchTitle', $searchTitle);
$sql->execute();
$result = $sql->fetchAll();
print_r($result);
foreach ($result as $row) {
echo "<li>" . " " . $row["title"]. " " . "</li>";
}
}
?>
<form name="searchBookTitle" method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>" >
<fieldset>
<legend>Search Books</legend>
<label for="txtSearchBookTitle">Search by Book Title</label>
<input type="text" name="txtSearchBookTitle" id="txtSearchBookTitle">
<input type="submit" value="Submit">
</fieldset>
</form>
<?php
include_once('getBooks.php');
getBooks();
include 'footer.php';
?>
You need to prepare the inputs this way:
$searchTitle = $_POST['txtSearchBookTitle'];
$sql = $db->prepare("SELECT title FROM tblBook WHERE title LIKE :searchTitle ORDER BY title");
$sql->execute(array(':searchTitle' => '%' . $searchTitle . '%'));
Or like this:
$searchTitle = $_POST['txtSearchBookTitle'];
$sql->bindParam(':searchTitle', "%{$searchTitle}%");
Use PDO::FETCH_ASSOC in your fetchAll.. it means it will return the data as an array
So make it like this one
$result = $sql->fetchAll(PDO::FETCH_ASSOC);
The search fusion works correctly but if I press submit with nothing in the search bar it shows all the data. how would I get a message to show up saying that nothing has been entered into the search bar ?.I am new to PHP.
<?php
$mysql_host="host";
$mysql_database="database";
$mysql_user="username";
$mysql_password="password";
$dbconnect=#mysql_connect($mysql_host, $mysql_user, $mysql_password);
// trys to connect to the database
if (!$dbconnect) {
exit("An error has occurred - could not connect to the database.");
// if couldn't connect, let the user know
}
if(!mysql_select_db($mysql_database)) {
exit("An error has occurred - Could not select the database.");
//if couldn't select db, let the user know
}
$output = '';
//collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM people WHERE firstname LIKE '%" . $searchq . "%' OR surname LIKE '" . $searchq . "';");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'There was no search results!';
} else {
while ($row = mysql_fetch_array($query)) {
$fname = $row ['firstname'];
$lname = $row ['surname'];
$id = $row ['id'];
$output .= '<div>'.$fname.' '.$lname.'</div>';
}
}
}
?>
<html>
<head>
<title>search</title>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="search" placeholder="Search here......." />
<input type="submit" value="submit" />
</form>
<?php print("$output");?>
</body>
</html>
If you want to avoid all of the results that are showing up when you submit the form, you need to check at what is being submitted in the text input.
Right now, if $searchq == "" then you're SQL query will search: WHERE firstname LIKE '%%' which is just a wildcard on anything.
In order to fix this, add $_POST['search'] != "" to the initial condition.
<?php
// Make sure to only perform the search and show the results if there's something to search for
if(isset($_POST['search']) && $_POST['search'] != "") {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM people WHERE firstname LIKE '%" . $searchq . "%' OR surname LIKE '" . $searchq . "';");
$count = mysql_num_rows($query);
if($count == 0) {
$output = 'There was no search results!';
} else {
while ($row = mysql_fetch_array($query)) {
$fname = $row ['firstname'];
$lname = $row ['surname'];
$id = $row ['id'];
$output .= '<div>'.$fname.' '.$lname.'</div>';
}
}
}
Now it will only search when the form has been submitted with a string to search with!
:)
I'm new here and I'm very new with php.
I am trying to make a search form with:
a dropdown list with two items: category and location;
a text field;
a search button.
It should work like this:
When "category" is selected, you enter a text and it will be searched only into categories.
When "location" is selected, your term will be searched among countries, states, zip codes.
I have a table with columns: id, name, category, country, zipcode, state.
Could somebody help me to understand why it doesn't display any results?
Here is my code:
<form action='search4.php' method='POST' name='form_filter'>
<b>Search</b><br>
<select name="selectVal">
<option value="category">category</option>
<option value="location">Country, state or zipcode</option>
</select>
<input type='text' name='search' placeholder='Enter text here...' size='50'><br>
<input type='submit' value='Send'>
</form>
<?php
// database connection
$db_host = "myhost";
$db_user = "myuser";
$db_password = "mypsw";
$db_name = "myname";
//connecting to database
$db = mysql_connect($db_host, $db_user, $db_password) or die ('Error - connection failed');
mysql_select_db($db_name, $db) or die ('Database selection error');
// retrieving search value we sent using get
$research = $_GET['research'];
// check if it has been sent, then it is ok
if ( $research == 'ok' ) {
// retrieving search value we sent using post
$search = $_POST['search'];
// check if the field has been filled
if ( $search == TRUE && $search != "" ) {
// character lenght more than 3
if ( strlen($search) >= 3 ) {
$search = mysql_escape_string(stripslashes($search));
}
if(isset($_POST['value'])) {
if($_POST['value'] == 'category') {
// query to get all categories
$query = "SELECT * FROM table_name WHERE category='$search'";
}
elseif($_POST['value'] == 'location') {
// query to get all country/state/zipcode records
$query = "SELECT * FROM table_name WHERE country='$search' OR zip_code='$search' OR state='$search'";
} else {
// query to get all records
$query = "SELECT * FROM table_name";
}
$sql = mysql_query($query);
while ($row = mysql_fetch_array($query)){
$Id = $row["Id"];
$country = $row["country"];
$category = $row["category"];
$name = $row['name'];
$zip_code = $row['zip_code'];
$state = $row['state'];
echo "Name: $name<br>";
echo "Zip_code : $zip_code<br>";
echo "State : $state<br>";
echo "Country: $country<br>";
echo "Category: $category<hr>";
}
}
}
}
?>
Thank you very much for your help.
You need to understand how to use <select> with php.
if you have this form:
<form method='post'>
<select name='example'>
<option value='e1'>example1</option>
<option value='e2'>example2</option>
</select>
</form>
You need to print it like that:
echo $_POST['example'];
In case the user selcted example1, the value will be e1.
In case the user selcted example2, the value will be e2.
You are using in your script $_POST['value']. It's just dosen't exist.
Try this, instead:
HTML FORM:
<form action='search4.php' method='POST' name='form_filter'>
<b>Search</b><br>
<select name="selectVal">
<option value="category">category</option>
<option value="location">Country, state or zipcode</option>
</select>
<input type='text' name='search' placeholder='Enter text here...' size='50'><br>
<input type='submit' value='Send'>
</form>
FORM PROCESSING:
<?php
// database connection
$db_host = "myhost";
$db_user = "myuser";
$db_password = "mypsw";
$db_name = "myname";
//connecting to database
$db = mysql_connect($db_host, $db_user, $db_password) or die ('Error - connection failed');
mysql_select_db($db_name, $db) or die ('Database selection error');
/*********************************************/
/***WHY DO YOU NEED THIS RESEARCH VARIABLE?***/
/*****WHAT IS ITS PURPOSE IN THIS SCRIPT?*****/
/*********************************************/
//GET CLEAN VERSIONS OF ALL NECESSARY VARIABLES:
$search = isset($_POST['search']) ? htmlspecialchars(trim($_POST['search'])) : null;
$catLocation = isset($_POST['selectVal']) ? htmlspecialchars(trim($_POST['selectVal'])) : null;
$query = "SELECT * FROM table_name WHERE ";
//YOU INDICATED YOU'D NEED TO RUN THE SEARCH-QUERY IF THE SEARCH-TERM AND SEARCH-SCOPE ARE DEFINED IE: NOT NULL; HOWEVER IF THE SEARCH TERM IS NOT GIVEN, YOU SELECT EVERYTHING IN THAT TABLE... (BAD PRACTICE, THOUGH)
if($catLocation){
if($search){
if($catLocation == "category"){
$query .= " category LIKE '%" . $search . "%'";
}else if($catLocation == "location"){
$query .= " country LIKE '%" . $search . "%' OR zip_code LIKE '%" . $search . "%' OR state LIKE '%" . $search . "%'";
}
}else{
$query .= "1";
}
$sql = mysql_query($query);
//HERE AGAIN WAS AN ERROR... YOU PASSED mysql_fetch_array A STRING $query INSTEAD OF A RESOURCE: $sql
while ($row = mysql_fetch_array($sql)){
$Id = $row["Id"];
$country = $row["country"];
$category = $row["category"];
$name = $row['name'];
$zip_code = $row['zip_code'];
$state = $row['state'];
echo "Name: $name<br>";
echo "Zip_code : $zip_code<br>";
echo "State : $state<br>";
echo "Country: $country<br>";
echo "Category: $category<hr>";
}
}