Search functionality outputting as 'array' - php

I followed a tutorial on how to make a search bar functional and I am not seeing what I'm doing wrong. I am trying to give users the option to search for products. The end result is everything is being out-putted as 'Array'. The correct amount of search results show up.
My search bar is on my index page.
<form class="searchbar" action="/searchresults" method="POST">
<input class="inputsearchbar" type="text"
name="search" size="50">
<input class="searchButton" type="submit" value="Search" name="submit">
</label>
</form>
I then have a page called searchresults.php where my results are outputted to. I'm pulling from my products table in my database.
I have this at the top of the file..
if(!isset($_POST['search'])) {
header("Location:index.php");
die($e->getMessage());
}
$con = mysqli_connect("localhost", "root", "", "bfb");
$search_sql = "SELECT * FROM products WHERE name LIKE '%" . $_POST['search'] . "%' OR description LIKE '%" . $_POST['search'] . "%'";
$search_query=mysqli_query($con, $search_sql);
if (mysqli_num_rows($search_query)!=0) {
$search_rs=mysqli_fetch_assoc($search_query);
}
?>
Followed by this in the body to output the results...
<h1>Search Results</h1>
<?php
if(mysqli_num_rows($search_query)!=0) {
do { ?>
<p><?php echo $search_rs=['name']; ?></p>
<p><?php echo $search_rs=['description']; ?></p>
<?php } while ($search_rs=mysqli_fetch_assoc($search_query));
} else {
echo"Sorry, no results were found. Please try again.";
}
?>
</div>
Why are all of my results displaying as 'Array' and how can I correct this?

take out the extraneous equal sign (=)
<?php echo $search_rs['name']; ?>

You have to use $_search_rs['name'] . Remove the extra '=' symbols.
Edit your PHP code as follows.
<h1>Search Results</h1>
<?php
if(mysqli_num_rows($search_query)!=0) {
do { ?>
<p><?php echo $search_rs['name']; ?></p>
<p><?php echo $search_rs['description']; ?></p>
<?php } while ($search_rs=mysqli_fetch_assoc($search_query));
} else {
echo"Sorry, no results were found. Please try again.";
}
?>

Related

How to stop print echo result in output without function executed

It might be a silly question but,
I created a single PHP to do some checks in my site and at the final result
I used echo to print it or print "nothing found" in case function failed
but the issue is, the PHP file keep printing the "nothing found" even if i didn't click the "submit" button
if (function failed) {
echo "not found";
} else {
echo "do stuff here";
}
the php file keep printing "not found"
I tried ob_clean() ob_end_flush() ob_end_clean() but it didn't work
Full code:
<!DOCTYPE html>
<html>
<head>
<title>Check IMDB</title>
</head>
<body>
<div class="container">
<form method="POST" action="">
<input type="submit" value=" Check IMDB ">
<div>
<textarea style="width: 50%; margin-top:7px; height: 150px;" id="urlbox" name="urlbox" placeholder="Add imdb links here (one per line)"></textarea>
</div>
</form>
</div>
<?php
$imdblink = "";
$imdblink = $_POST['urlbox'];
?>
<?php
set_time_limit(0);
require(dirname(__FILE__) . '/wp-load.php');
global $wpdb;
echo "<br>";
if (!preg_match_all('~tt\d{7,8}~', $imdblink, $ttids)) {
echo "no ttids found";
} else {
$resultSet = $wpdb->get_results("SELECT meta_value FROM wp_postmeta WHERE meta_key = 'imdb' AND meta_value IN ('" . implode("','", $ttids[0]) . "');");
$foundInDatabase = array_column($resultSet, "meta_value");
foreach ($ttids[0] as $index => $ttid) {
if (in_array($ttid, $foundInDatabase)) {
$ttid = '<a style="color:blue;" href="https://www.imdb.com/title/'.$ttid.'/">'.$ttid.'</a>';
}
echo "<div>" , ($index + 1) , "- {$ttid}</div>\n";
}
}
?>
</body>
</html>
You should add a name attribute to your submit button and check if the button was pressed.
In your case, you are checking the urlbox everytime you run the script.
<input type="submit" name="submit" value=" Check IMDB ">
<?php
if(isset($_POST['submit'])) {
//Here add your code
}
?>
No the script will check the urlbox only when the button is pressed.

Getting a value from a database and echoing from another file

I am trying to Select a row from a database table and display the variables in another PHP file. Right now I have to trying just one variable, but will change to outputting a table later on. The error is an Undefined Variable:output.
I have tried using session but it prints out the array and doesn't go all the way through. I really just want the variable so that I can put them into a table easier.
My store file, which shows a search bar and where I am trying to display the results, under the search bar.
<?php
require "header.php";
?>
<main>
<form action="includes/itemsearch.php" method="get">
Please enter the Item you are looking for:<br>
<input type="text" name="item" placeholder="Search for an item...">
<br><br>
<button type="submit" name="search-submit">Search</button>
</form>
<?php echo $output ?>
</main>
<?php
require "footer.php";
?>
My item search file:
<?php
if (isset($_GET['search-submit'])) {
require 'connect.php';
$item = $_GET['item'];
$output = "";
$sql = "SELECT * FROM Product";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($result)){
$pName =$row['Product_Name'];
$manufacture=$row['Manufacture'];
$quantity=$row['Quantity'];
$price=$row['Price'];
$description=$row['Description'];
echo"<p>$pName</p><br />";
}
header("Location: ../store.php?");
}
I currently get an undefined variable error.
use post method instead of get
<?php
if (isset($_POST['search-submit'])) {
}
?>
$output is undefined because you initialize it on click of submit button so <?php echo $output ?> is executing first then it gets initialized.
try
<?php
if (isset($_GET['search-submit'])){
echo $output;
}
?>
to get output just require search file in store.php
// store.php
<?php
require "header.php";
require "search.php";
?>
<main>
<form action="" method="get">
Please enter the Item you are looking for:<br>
<input type="text" name="item" placeholder="Search for an item...">
<br><br>
<button type="submit" name="search-submit">Search</button>
</form>
<?php echo $output ?>
</main>
<?php
require "footer.php";
?>
this is the final code
// search.php
<?php
if (isset($_GET['search-submit'])) {
require 'connect.php';
$item = $_GET['item'];
$output = "";
$sql = "SELECT * FROM Product";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($result)){
$pName =$row['Product_Name'];
$manufacture=$row['Manufacture'];
$quantity=$row['Quantity'];
$price=$row['Price'];
$description=$row['Description'];
$output .= "<p>$pName</p><br />";
}
}
?>
// store.php
<?php
require "header.php";
require "search.php";
?>
<main>
<form action="" method="get">
Please enter the Item you are looking for:<br>
<input type="text" name="item" placeholder="Search for an item...">
<br><br>
<button type="submit" name="search-submit">Search</button>
</form>
<?php echo isset($_GET['search-submit']) ? $output : '' ?>
</main>
<?php
require "footer.php";
?>

my data isnt inserting into mySQL data table with php

I need help on my code. When data is entered on my site, it does not show up in the mySQL data table. The insert function that I used might be the problem, but I cannot figure out how to get it to actually insert and show up in my table in my database. Can someone please guide me in the right direction with my code?
<?php
session_start();
include("db_connect.php");
if(isset($_POST['submit'])){
$item = $_POST['item'];
if(empty($item)) {
$errors = "you must enter something";
}
else{
mysqli_query("INSERT INTO a4_todolist (item) VALUES ('$item')");
header('location: index.php');
}
}
$a4_todolist = mysqli_query("SELECT * FROM a4_todolist");
?>
<!DOCTYPE html>
<html>
<head>
<title> Assignment 4 - To Do List </title>
<link rel ="stylesheet" type ="text/css" href="style.css">
</head>
<body>
<div class "head">
<h2> To Do </h2>
</div>
<form method= "POST" action = "index.php">
<?php if (isset($errors)) { ?>
<p><?php echo $errors; ?></p>
<?php } ?>
Item <input type = "text" name= "item" class="item_input">
Author <input type = "text" name= "author" class="author_input">
<button type = "submit" class="add-btn" name="submit"> Add Task
</button>
</form>
<table>
<tbody>
<?php while ($row = mysqli_fetch_array($a4_todolist)) { ?>
<tr>
<td class="id"> <?php print $row['id']; ?> </td>
<td class="item"> <?php echo $row['item']; ?> </td>
</tr>
<?php } ?>
</tbody>
</table>
</thread>
</body>
</html>
You have missed the sql connection variable which is coming from db_connect.php file inside your mysqli_query. Your mysqli_query() should be like this
mysqli_query($connection,"INSERT INTO a4_todolist (item) VALUES ('$item')");
Also this
$a4_todolist = mysqli_query($connection,"SELECT * FROM a4_todolist");
It seems that you are a beginner so I recommend you to learn Prepared statements which is more efficient and safe to use.
You should pass the connection link identifier as well as you can check for errors.
$con = mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
Also after executing query you can again check for error.
if (!mysqli_query($con,"INSERT INTO a4_todolist (item) VALUES ('$item')")) {
echo("Error description: " . mysqli_error($con));
}

Show single listing from Search - PHP SQL

Hopefully the last question as I am not 100% sure how to solve this one.
I did see a similar question , but it does not really reflect my question and the other question is quite difficult to follow , so please see this as a original question and not a duplicate..
So on my website someone carried out a search from a search bar using the 'POST' method , teh search results show all whiskies in the databse. I have a number of whiskies with the same name but with different dates and prices. I would like it just to show one of each type that was searched for rather than all of them. I have attahced a clip of the databse. Really appreciate the help
Thanks
Index.php
</head>
<?php
$page='index';
include('header.php');
include('navbar.php');
?>
<script type="text/javascript">
function active(){
var search_bar= document.getElementById('search_bar');
if(search_bar.value == 'Search for your whisky here'){
search_bar.value=''
search_bar.placeholder= 'Search for your whisky here'
}
}
function inactive(){
var search_bar= document.getElementById('search_bar');
if(search_bar.value == ''){
search_bar.value='Search for your whisky here'
search_bar.placeholder= ''
}
}
</script>
<body>
<div class="third_bar">
<div class="background_image">
</div>
<div class="form"><form action= "search.php" method="post">
<input type="text" name="search" id="search_bar" placeholder="" value="Search for your whisky here" max length="30" autocomplete="off" onMouseDown="active();" onBlur="inactive();"/><input type="submit" id="search_button" value="Go!"/>
</form>
</div> </div>
</body>
</div>
<?php include ('footer.php');
?>
Search.php
<?php
$page='search';
include('header.php');
include ('navbar.php');
echo "<br>";
include ('connect.php');
if (isset ($_POST['search'])) { //the 'search' refers to the 'search' name=search on the index page and makes does something when the search is pushed.
$search = $_POST['search'];
$search = "%" . $search . "%"; // MySQL wildcard % either side of search to get partially matching results
// No wildcard if you want results to match fully
} else {
header ('location: index.php');
}
$stmt = $conn->prepare("SELECT * FROM test_db WHERE name LIKE :name ORDER BY name ASC"); // Use = instead of LIKE for full matching
$stmt->bindParam(':name', $search);
$stmt->execute();
$count = $stmt->rowCount(); // Added to count no. of results returned
if ($count >= 1) { // Only displays results if $count is 1 or more
echo "<div class='results_found'>";
echo $count;
echo " results found<br>";
echo "</div>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<div class='results'>";
echo "<div class='result_name'>";
echo "<b>Whisky Name:</b><br>";
echo "<a href='details1.php?id={$row['lot_id']}' >{$row['name']}</a>";
echo"<br>";
echo "</div>";
echo "</div>";
}
} else {
echo " Sorry no records were found";
}
?>
</htm

very slow search results - mysqli - php

I'm just learning how to do this so please forgive my ignorance!
This page loads VERY slow and the search almost doesn't run on my iphone (sometimes timesout).
Here is my test site: http://webtestkit.com/1KaraokeDJ/index.php
$view=$db->query("select * from 1KaraokeDJ where
Title like '%$data%' ||
Artist like '%$data%' ||
Disc like '%$data%' ||
Brand like '%$data%'
limit 50");
is there a better way to do this search?
There are 28,000+ records now, but it will be in the 100k range later.
here is the full code:
<?php
include("connect.php");
session_start();
if(isset($_POST['submit']))
{
$search=$_POST['search'];
$_SESSION['title']= $search;
if(($_SESSION['title'])!="")
{ header("location:index.php"); }
else
{ echo "<script> alert('Please enter something to search for') </script>"; }
}
?>
<html>
<head>
<title>1KaraokeDJ.com</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="login">
<form method="post">
<p><img src="top.jpg" /></p>
<p>
<?php if(isset($_SESSION['title'])) { ?>
<input name="search" type="search" list="searchkey" value="<?php echo $_SESSION['title'];?>" class="search" />
<?php } else { ?>
<input name="search" type="search" list="searchkey" placeholder="Just type your text here and press enter - ex : Abba" class="search" />
<?php } ?>
</p>
<datalist id="searchkey">
<?php
$tile=$db->query("SELECT * FROM `1KaraokeDJ`");
while($storetitle=mysqli_fetch_object($tile))
{ ?>
<option value="<?php echo $storetitle->title ?>">
<?php } ?>
</datalist>
<p><input type="submit" name="submit" id="click" class="searchbutton" value="Karaoke Search" /></p>
<hr style="width:100%">
<?php if(isset($_SESSION['title'])) {
if(($_SESSION['title']!=""))
{
$data=$_SESSION['title'];
$view=$db->query("select * from 1KaraokeDJ where
Title like '%$data%' ||
Artist like '%$data%' ||
Disc like '%$data%' ||
Brand like '%$data%'
limit 50");
$check=mysqli_num_rows($view);
if($check!="")
{ while($descri=mysqli_fetch_object($view)) { ?>
<div class="reslt">
<h3 id="results">
<?php
echo str_replace($data, '<span class="highlight">'.$data."</span>", $descri->Artist);
echo " - ";
echo str_replace($data, '<span class="highlight">'.$data."</span>", $descri->Title);
?>
</h3>
<p class="Description">
<?php
echo str_replace($data, '<span class="highlight">'.$data."</span>", $descri->Brand);
echo " - ";
echo str_replace($data, '<span class="highlight">'.$data."</span>", $descri->Disc);
echo " - ";
echo $descri->Track;
?>
<p>
<hr>
</div>
<?php } ?>
<p><?php echo $check ?> Results</p>
<p class="highlight">Showing Up To 50 Results - Try Refining Your Search</p>
<?php } else { ?>
<div class="reslt">
<h3 id="results">Nothing Found!</h3>
<p class="Description">Try Changing Your Search Terms<p><hr>
</div>
<?php } } } ?>
</form>
</div>
</body>
</html>
Your answer is:
Place full-text indexes on your columns. Use match instead of like to actually use said indexes
an example of match
WHERE MATCH(field1 , field2) AGAINST ('aaa*' IN BOOLEAN MODE)
manual for match
http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
<datalist id="searchkey">
<?php
$tile=$db->query("SELECT * FROM `1KaraokeDJ`");
while($storetitle=mysqli_fetch_object($tile))
{ ?>
<option value="<?php echo $storetitle->title ?>">
<?php } ?>
</datalist>
for whatever reason, saving a datalist to the client browser is very slow!

Categories