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'];
Related
I'm connected to phpmyadmin but I can not get any data from phpmyadmin.
my php version is 7.2.9 , I made everything that I wanted in database but php can't show the data in site ( I'm using localhost ).
here is the code:
<?php
$key = $_GET['key'];
$terms = explode(" ", $key);
$query = "SELECT * FORM search WHERE ";
foreach ($terms as $each){
$i++;
if($i == 1){
$query .= "keywords LIKE '%$each%' ";
} else{
$query .= "OR keywords LIKE '%$each%' ";
}
echo $query;
}
//connection
mysql_connect("localhost", "root", "");
mysql_select_db('search');
$query = mysqli_query($query);
$numrows = mysqli_num_rows($query);
if($numrows > 0){
while ($row = mysql_fetch_assoc($query)){
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo "<h2><a href='$link'>$title</h2></a>
$description<br /><br />";
}
}
else{
echo "No results found for \"<b>$key</b>\""; }
//disconnect
mysql_close();
?>
You have a couple of mistakes in your PHP/HTML. I'm gonna sum them up here so you can take a look at them:
<h2><a href='$link'>$title</h2></a>$description<br /><br /> This is wrong HTML. Close your a tag inside the h2.
You are connecting to you database through mysql, but querying through mysqli. Connect to your database with mysqli. Mysql_ family of functions have been removed in PHP 7
You have a typo in your query. you have written FORM instead of FROM.
You are exploding your $_GET variable on spaces. But i doubt if a $_GET variable has any spaces to begin with... Check if this is true.
first of all mysql_connect() is not anymore available after php 5. Instead of using mysql use mysqli_connect(). Please how to make connection and query database using php7 here.
https://www.w3schools.com/php/func_mysqli_fetch_row.asp
If still you have problem. Ask for help in comments.
<?php
$query = "SELECT * FORM search WHERE ";
foreach ($terms as $each){
$i++;
if($i == 1){
$query .= "keywords LIKE '%$each%' ";
} else{
$query .= "OR keywords LIKE '%$each%' ";
}
echo $query;
}
//connection
$conn = mysqli_connect("localhost", "root", "","search");
if(!$conn)die("Connection Error");
$query = mysqli_query($conn,$query);
if(!query)die("query error");
$numrows = mysqli_num_rows($query);
if($numrows > 0){
while ($row = mysqli_fetch_assoc($query)){
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo "<h2><a href='$link'>$title</h2></a>
$description<br /><br />";
}
}
else{
echo "No results found for \"<b>$key</b>\"";
}
You are mixing up mysqli and mysql. I have edited your stuff. Please try. Don't forget to fix the portion marked [missing]
<?php
$key = $_GET['key'];
$terms = explode(" ", $key);
foreach ($terms as $each){
$i++;
if($i == 1){
$query .= "keywords LIKE '%$each%' ";
} else{
$query .= " description OR keywords LIKE '%$each%' ";
}
echo $query;
}
//connection
$conn=mysqli_connect("localhost", "root", "");
mysqli_select_db($conn, 'search');
if($result= mysqli_query($conn, $query)){
$numrows = mysqli_num_rows($result);
}
if($numrows > 0){
while($row = mysqli_fetch_array($result)){
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
//echo "<h2><a href='$link'>$title</h2></a>
//$description<br /><br />";
echo '<h2><a href="' . $link . '">' . $title .
'</h2></a>' . $description . '<br /><br />';
}
}
else{
echo "No results found for \"<b>$key</b>\""; }
//disconnect
mysqli_close();
?>
Here's the Full working Example TESTED at my end (Last night I wasn't at my work machine and couldn't test the code.Later I created a small db and Tested it. I had searched with the dummy key 'ram mary albert' in my example
<?php
$key = $_GET['key'];
$terms = explode(" ", $key);
$qu1 = "SELECT * FROM search WHERE ";
$qu2 = "order by id ASC";
$conn=mysqli_connect("localhost", "root", "");
mysqli_select_db($conn, 'search');
for($i=0; $i< count($terms); $i++){
$query = $qu1 . " keywords LIKE '%$terms[$i]%' " . $qu2;
echo( $query . "<br>" );
$resulter= mysqli_query($conn, $query);
while($row = mysqli_fetch_array($resulter)){;
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
$EscLink='\'' . $link . '\'';
echo ('<a href="javascript:void(0)" onClick="alert(' .
$EscLink . ')">' . $title . '</a><br>' . $description .
'<br /><br />');
} // Close While
} // Close for
//disconnect
mysqli_close($conn);
?>
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 want to fetch database value in html tag, is it possible ?? I can fetch database value in textbox using this code
$con = mysqli_connect("localhost", "root", "", "hct_db"); // Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$client_id = mysqli_real_escape_string($con, $_POST['client_id']);
$result = mysqli_query($con, "SELECT * FROM client where client_id = '" . $client_id . "'");
while ($row = mysqli_fetch_array($result)) {
<input class="form-control" name="client_id1" value="<?php echo( htmlspecialchars( $row['address'] ) ); ?>" />
Try this (it will fill your input boxes with the value)
<?php
$con = mysqli_connect("localhost", "root", "", "hct_db"); // Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$client_id = mysqli_real_escape_string($con, $_POST['client_id']);
$result = mysqli_query($con, "SELECT * FROM client where client_id = '" . $client_id . "'");
echo '<form action="" method="post">';//openning upthe
while ($row = mysqli_fetch_array($result)) {
echo '<p>'.( htmlspecialchars( $row['address'] ) ).'</p>';
}
Yes, you can do it. At first, retrieve your data using query and keep it an array and then echo it.
yes you can try this and pls try something before posting a question...
<?php
$con=mysqli_connect("localhost","root","","hct_db"); // Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} // escape variables for security
$client_id = mysqli_real_escape_string($con, $_POST['client_id']);
$result = mysqli_query($con,"SELECT * FROM client where client_id = '".$client_id."'");
while($row = mysqli_fetch_array($result)) { //this is my retrieve code, what to do next ? ?>
<? echo $row[0]; ?> // href tag
<h2><? echo $row[0]; ?></h2> //h tag
<p><? echo $row[0]; ?></p> //p tag
//and so on
<?}?>
comment for further querys...
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>";
}
}