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
Related
The user suppose to input first name or last name into a search bar in a web-page and it suppose to list attributes from the table into the web-page. No matter what I type into the search bar, nothing is outputted. I followed this video on how to search in php. I tried looking at it over an hour but I can't find anything wrong. I get no error messages in my webpage.
<?php
$serverName = 'localhost';
$userName = 'root';
$password = '';
$databaseName = 'project3';
$connection = mysqli_connect($serverName, $userName, $password,
$databaseName);
if (!$connection) {
die("Connection Failed: " . mysqli_connect_error());
}
echo "Connected Successfully!! <br>";
$output = '';
if (isset($_Post['search'])) {
$searchq = $_Post['search'];
$searchq = preg_replace("#[^0-9a-z]#i", "", $searchq);
$query = mysqli_query("SELECT * from employee WHERE fname LIKE
'%$searchq%' OR"
. "lname LIKE '%$searchq%") or die("failed");
$count = mysqli_num_rows($query);
if ($count == 0) {
$output = 'No search results';
} else {
while ($row = mysqli_fetch_array($query)) {
$firstname = $row['fname'];
$lastname = $row['lname'];
$id = $row['id'];
$output .= '<div>' . $firstname . '' . $lname . '</div>';
echo "hi";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Database Webpage</title>
<font color ="white">
<h1 style="background-color:black; text-align: center">Datebase Website</h1>
<font color ="black">
</head>
<body>
<form action = "index.php" method = "POST">
<input type = "text" name ="search" placeholder="Search"/>
<input type= "submit" value = ">>"/>
</form>
<?php print("$output"); ?>
</body>
</html>
The mysqli_query does need 2 parameters, as the PHP api shows with the procedural form that you have.
So, for that part, the call should look like this:
$query = mysqli_query($connection, "SELECT * from employee WHERE fname LIKE
'%$searchq%' OR"
. "lname LIKE '%$searchq%") or die("failed");
However, there will be trouble with the query. Note this portion of the query:
'%$searchq%' OR" <--- No space after the OR
. "lname LIKE '%$searchq%")
^--- No space before lname
Either one of the those 2 areas needs a space.
That last part of the query string will ultimately look like this:
'%$searchq%' ORlname LIKE '%$searchq%
^--- trouble (no space) ^---and trouble here (missing a closing single quote)
Sometimes it is useful to set the query separately, so that you can echo it out to check that it is syntactically correct as far as spacing around keywords, columns, values, comma usage (when needed), proper quoting, etc.
Consider this difference:
$query = "SELECT * from employee WHERE fname LIKE '%$searchq%' OR "
. "lname LIKE '%$searchq%'";
// query check (delete after validation, or comment-out)
echo $query;
$result = mysqli_query($connection, $query);
// I like to use $result, as the query call will return a result set with SELECT
// or false with failure. (though it can return true for other query types, see the api link)
It can also helpful to output the error as part of the die message:
if (!$result) { // Doh! something wrong...
die('failed: ' . mysqli_error($connection));
} else {
$count = mysqli_num_rows($result); // check the result count
if ($count == 0) {
$output = 'No search results';
} else {
while ($row = mysqli_fetch_array($result)) { // fetch a row
$firstname = $row['fname'];
$lastname = $row['lname'];
$id = $row['id'];
$output .= '<div>' . $firstname . '' . $lname . '</div>';
echo "hi";
}
}
}
HTH
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 am running the following code and I cannot display anything on the page after the search is run. I know the connection is correct and that the search query is being loaded, so it must be something functionally wrong
<?php
$title = $_POST['search'];
echo $title ;
$con = mysqli_connect("localhost", "user", "password") or die ('Could not connect, this is the error: ' . mysql_error());
mysqli_select_db($con,"db") or die ('Sorry could not access database at this time. This is the error: ' . mysql_error());
if(isset($_POST['search']){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$search_sql = "SELECT title FROM gamereview WHERE tags LIKE '%".$_POST['search']."%' ";
$search_query = mysqli_query($con, $search_sql) or die("could not search");
$count = mysqli_num_rows($query);
if($count==0){
$output = 'THere was no search results!';
} else
while ($row = myqli_fetch_array($query, MYSQLI_BOTH)){
$title = $row['title'];
$id = $row['id'];
$output .= '<div>' .$id.' '.$title.'</div>';
}
}
echo $output;
mysql_close($con);
?>
You have assigned $_POST['SEARCH'] to a variable $searchq, yet you are not passing $searchq in your select statement. Also fix the myqli_fetch_array typo!!
$search_sql = "SELECT title FROM gamereview WHERE tags LIKE '%".$searchq."%' ";
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>";
}
}