php mysql search engine not finding results - php

I am trying to make simple search engine. My problem is every code I am trying is bringing me same result "Found 0 results." My database is populated and when I put my SQL query into it, it gives me back result I look for.
I tried this code as well from stackoverflow php search engine script that did bring back 1 result for person asking that question and all I am getting is message "Sorry, there are no matching result". To write this code I followed youtube tutorial by phpacademy step by step and again same thing happened. I read all the comments under the tutorial to see if anyone came across same problem but it did work fine for everyone. I have no idea what I am doing wrong and would really appreciate if someone could help me.
That is form from my html file:
<body>
<form action="eatsearch.php" method="get">
<label>
Search
<input type="text" name="keywords" placeholder = "Type to search..">
</label>
<input type="submit" value="Search">
and this is my php:
<?php
require_once('config.php');
if(isset($_GET['keywords'])) {
$keywords = $connect->escape_string($_GET['keywords']);
$query = $connect->query("SELECT rname, tel, url, food
FROM general WHERE food LIKE '%{keywords}%'");
?>
<div class="result-count">
Found <?php echo $query->num_rows; ?> results.
</div>
<?php
if($query->num_rows) {
while($result = $query->fetch_object()) {
?>
<div class = "result">
<?php echo $result->rname;?>
</div>
<?php
}
}
}
?>

Keywords without $?
Put a $keywords

Your error is here:
$query = $connect->query("SELECT rname, tel, url, food FROM general WHERE food LIKE '%{keywords}%'");
It should be:
$query = $connect->query("SELECT rname, tel, url, food
FROM general WHERE food LIKE '%{$keywords}%'");
You forgot your $ sign in front of the keywords variable.

Related

How to select specific data from one table and insert a part of it back to another table by user action

I am pretty new to PHP and MySQL. Anyway, I currently try to write an application for Karaoke events.
The visitors of the event should be able to search online in a database for a specific song they would like to sing and then should be able to add this song to a kind of queue. The queue can then be display on a screen so the visitors can see how many people are singing before them and what they are singing etc.
My msql database is pretty simple. The table is called "songs" and I have 4 columns
id, title, artist, language
So first thing I need is a search form in which the people can type in any kind of searchterm and they get back the matching songs. It should not matter weather they search for artist or song, so they could type in "Love" as well es "Beatles" ot get the matching results.
So if the searchterm is "love" for example, the visitor gets back a table of maybe 100 lines of songs with the term "love" in the title.
I finally made this work, here is my code so far
<form action="searchform.php" method="get" >
<input type="text" name="searchquery" dir="ltr">
<input type="submit" value="start search">
</form>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'inc/db.php';
$daten = array();
if(isset($_GET ['searchquery']) && $_GET['searchquery'] !== ' ')
{
$searchquery= trim($_GET['searchquery']);
echo "<p>Your search was: <b>". $searchquery ."</b></p>";
$search_for = "%$searchquery%";
$songsearch=$db->prepare("SELECT title,artist FROM songs WHERE artist LIKE ? OR title LIKE ?");
$songsearch->bind_param('ss', $search_for, $search_for);
$songsearch->execute();
$songsearch->bind_result($showtitle, $showartist);
echo "<table><tr><th>Title</th><th>Artist</th></tr>";
while ($songsearch->fetch()) {
echo "<tr><td>$showtitle</td>";
echo "<td>$showartist</td></tr>";
}
echo "</table>";
}
?>
inc/db.php
<?php
error_reporting(E_ALL);
$db = new mysqli('localhost', 'root', 'root', 'songlist');
$db->set_charset('utf8');
?>
Now I want the visitor to be able to click on one songtitle of the returned list (table) and with this click I want the song to be added to a queue. My idea was to just add another table to the database called "queue" with the columns id,title,artist and to add the choosen song to this table using the "INSERT" command.
Something like this...
$addtoqueue= $db->prepare("INSERT INTO queue (title, artist) VALUES (?, ?)");
After adding a song to the queue, it should forward to a "queue.php" which displays the data from the queue-table and refreshes every 30 seconds or so.
So I would probably need some kind of "action" around the
echo "<tr><td>$showtitle</td>";
line...like
<tr><td>$showtitle</td>
But I have no idea how to "select" the specific dataset on which the visitor has clicked so that all columns of this dataset are inserted to the "queue" table.
p.s. I now tried the following, however I get errors on this and not the expected result of course
$queuedata = array();
if (isset($_GET['action']) and $_GET['action']=='queue') {
if ( isset($_GET['id']) ) {
$id_fetch = (INT) $_GET['id'];
if ($id_fetch > 0)
{
$dsfetch=$db->prepare("SELECT id, title, artist FROM songs WHERE id = ?");
$dsfetch->bind_param('iss', $id, $title, $artist);
$queuedata[] = $dsfetch;
}
}
$addqueue = $queuedata->prepare("INSERT INTO queue (id, title, artist) VALUES ('$id, $title, $artist')");
$addqueue->bind_param('sss', $id, $title, $artist);
if ($addqueue->execute()) {
header('Location: queue.php?action=feedback');
die();
}
}
if (isset($_POST['action']) and $_POST['action']=='feedback') {
echo '<p class="feedbacksuccess">Song successfully added to queue</p>';
}
and for the output
echo "<tr><td><a href=\"?action=queue&id=$queuedata->id;\">$showtitle</td>";
I get this error:
Error: Notice: Trying to get property of non-object in C:\xampp\htdocs\karaoke-files\suchtest2.php on line 55
I am also new to programming, but I will try to help out.
If I understand you need to make a selection and then send info to a php script.
Problem is that php is server side language, as far as I understand.
You need something to do the work on the front-end of things. So look up some javascrpt.
You can include bundle.js into your index file, and you it's functions for selecting items.
I will give some small examples of code that you can easily find online.
For example. Use javascript to select needed things.
And you function to make to do the work on the front-end.
<button id="1" onClick="reply_click(this.id)">B1</button>
<button id="2" onClick="reply_click(this.id)">B2</button>
<button id="3" onClick="reply_click(this.id)">B3</button>
<script type="text/javascript">
function reply_click(clicked_id)
{
alert(clicked_id);
}
</script>`
Using javascript you can also call php script.
Read this post Call php function from javascript
Or you can simply use html form. You can fill it up with php using echo. In action you can specify what php to send data to.
<form action="action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
And php script you are calling in this case action_page.php
can receive your input like so $firstName = $_REQUEST['firstname'];
And if you want for example to populate you form's drop down box and fill it with data you can read this post Populate a Drop down box from a mySQL table in PHP
It is a bit long answer, hope it will help you.
I finally found a solution
if (isset($_GET['action']) and $_GET['action']=='queue') {
if ( isset($_GET['id']) ) {
$id_fetch = (INT) $_GET['id'];
if ($id_fetch > 0)
{
$dsfetch=$db->prepare("SELECT id, title, artist FROM songs WHERE id = ?");
$dsfetch->bind_param('i', $id_fetch);
$dsfetch->execute();
$dsfetch->bind_result($id, $title, $artist);
while ($dsfetch->fetch()) {
echo $id . ' / '. $title .' '. $artist;
}
$addqueue = $db->prepare("INSERT INTO queue (id, title, artist, user) VALUES (?, ?, ?, ?)");
$addqueue->bind_param('isss', $id, $title, $artist, $name);
if ($addqueue->execute()) {
header('Location: index.php?aktion=feedback');
die();
}
}
}
}
if (isset($_GET['aktion']) and $_GET['aktion']=='feedback') {
echo '<p class="feedbacksuccess">Song has been added to queue</p>';
}
and later in the output
echo "<tr><td>$showtitle</td>";
Not sure wether or not this is "good code", but it works :-)
Thanks for all the hints

Making a search engine using PDO/PHP

I'm trying to write a search engine using pdo/php but I am a beginner still in programming and I need ur help!
The search engine's results should be displayed on the same page as the engine. (preferably in a table)
I have been trying to play with various MySql scripts I got from tutorials and w3schools.com but I can't figure this out:
How do I write the piece of code that makes my search.php select from my DB_table what is being searched for in the search engine?
Been trying this last time using mysql :
<form action='./search.php' method='get'>
<input type='text' name='k' size='50' value='<?php echo $_GET['k']; ?>' />
<input type='submit' value='Search' />
</form>
<hr />
<?php
$k = $_GET['k'];
$terms = explode(" ", $k);
$query = "SELECT * FROM Callflow WHERE ";
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "keywords LIKE '%$each%' ";
else
$query .= "OR keywords LIKE '%$each%' ";
}
<?php
$db = new PDO('mysql:host=localhost;dbname=voizxl_wachtrij;charset=utf8', 'root', '');
?>
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)){
$id = $row['calliipid'];
$title = $row['calleridname'];
$keywords = $row['calleridnum'];
echo "<h2><a href='$title'</a></h2>
$keywords<br /><br />";
}
}
else
echo "No results found for \<b>$k</b>\"";
mysql_close();
?>
Only when I tried this code I got errors, but I post it so u can see what i'm trying to achieve.
Now in PDO I can't figure out how to write this..
I'm experimenting with codes like :
<?php
$db = new PDO('mysql:host=localhost;dbname=voizxl_wachtrij;charset=utf8', 'root', '');
?>
<?php
foreach($db->query('SELECT * FROM Callflow') as $row) {
echo $row['calleridname'];
}
?>
<?php
$stmt = $db->prepare("SELECT * FROM Callflow WHERE id=:id AND name=:name");
$stmt->execute(array(':name' => $name, ':id' => $id));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<?php
$stmt = $db->query('SELECT * FROM table');
$row_count = $stmt->rowCount();
echo $row_count.' rows selected';
?>
Could someone please help by explaining the logic in writing the code or by giving an example of how to achieve what I want? Would be very much appreciated! TY in advanced!
Well by all means thank you for your honesty but what do you expect from someone who is a beginner?
There is one thing. An essential one.
It's about programming.
Most people take it as a sort of hobby, an easy-go thing. But never as a profession which require years of education and experience.
Most people never take programming seriously, like surgery or nuclear physics. So, all their idea of education is to ask someone to guide.
However, the truth is:
YES. Sometimes you are just unable to solve whatever particular task because of lack of education or experience. One cannot build a skyscraper by asking questions on a forum.
If you are a beginner - then you need to learn. Learn basic elements. Learn to create simpler applications. Spend time. And then eventually be able to accomplish more complex tasks without asking people to write all the code for you.
If you can't get any help from dozens of similar questions - then you need to learn first to be able to understand the code from answers.
But again - there is nothing wrong if you can't accomplish your search at once. We all had to learn. We all were unable to do it one day and we all had to grow up first.

GET POST mysql data on next page

Ok, I haven't done much of this sort of stuff, so I am clueless right now.
On the first page you hit the form submit that generates a bunch of information/stuff and displays it underneath submit button, but I don't know how to take the displayed information and use it on the next page I will show some of my code. btw I know the code is bad, just ignore that fact.
<form name="input" action="slaymonster.php" method="post" id="id">
<div align="center">
<input name="Submit" id="Submit" type="submit" class="button" value="Explore Map!"/>
</div>
</form>
if (isset($_POST['Submit'])) {
include 'includes/mapstuff.php';
// So here we pick a random row from the table pokemon notice the order by rand
$sql23 = "SELECT * FROM map1pokemon ORDER BY RAND() LIMIT 1;";
// We then check for errors
$result23 = mysql_query($sql23) or die(mysql_error());
// we then make the result into a virable called battle_get23
$battle_get23 = mysql_fetch_array($result23);
$sql2 = "SELECT * FROM pokemon WHERE name='".$battle_get23['pokemon']."'";
$result2 = mysql_query($sql2) or die(mysql_error());
$battle_get2 = mysql_fetch_array($result2);
// Now we need to make sure the image is safe be for we use it
$pic2= mysql_real_escape_string($battle_get2['pic']);
$pic = strip_tags($pic2);
include 'includes/maptypes.php';
?>
<form name="inputt" action="" method="post">
<div align="center">
<input type="submit" class="catch" value="Catch Pokemon" name="catch">
</div>
</form>
<p></p>
<?php
echo "You have just found a " ;
echo $randomview97[0];
echo " ";
echo $battle_get23['pokemon'];
$_SESSION['pokemon'] = $battle_get23['pokemon'];
$_SESSION['type'] = $randomview97[0];
$_SESSION['pic'] = $battle_get2;
$_SESSION['money'] = $randomview2[0];
$_SESSION['level'] = $randomview3[0];
$_SESSION['ticket'] = $randomview4;
?>
<p></p>
<?php
echo "You have gained ".$randomview3[0]." levels" ;
echo " ";
?>
<p></p>
<?php
echo "You have received $".$randomview2[0]."" ;
echo " ";
?>
<p></p>
<?php
echo "</center>";
}
?>
it displays the pokemon's picture it's name, type,amount of money you got ect...
I need all that information to be useable on the next page.
Any help is appreciated :)
At the top of your PHP code, be sure to include session_start();
You are already using session variables, so you should refer here to see what a PHP session is: PHP session_start() - Manual. It makes sure to do exactly what you are asking for (someone may point out that in certain cases session_start(); is not necessary, but for your purposes, while learning, stick to the Manual for best practices)
This information will be usable on the next 'page', just as the manual describes, and will be available, until you call something like session_destroy().
If you want to pass the information from one page to another. You have to put the result inside the form tag. Then it is possible to pass the information to another page. Or you can put it on the session and get information from any page.
you got my point? If you explain what you want to do. Then I will do something for you.

Selecting row from DB using mysql/php

I'm trying to get a row from the DB using php, i've made an html form that's supposed to take a book title from users and gets the review from the DB about this book, and then post it in an input text, the form's action leads to the following function :
function GetReview($BookTitle)
{
require'DB.php';
if(empty($_POST['BookTitle']))
{
echo " You must enter a book name!";
return false;
}
$BookTitle = mysql_real_escape_string($BookTitle);
$q="Select Reviews from Users_Booklist where (Book_Title like '%" .$BookTitle."%');";
if(!mysql_query($q,$con))
{
die("Error".mysql_error());
}
else
{
$row = mysql_fetch_row($q);
?>
<html>
<head><title>Delete Review </title>
</head>
<body>
<br>
<form name="DeleteReview " action="DeleteReviewsFunction.php" method="post">
Review: <input type="text" name="Review" size="200" value="<?php echo $row[0]; ?>"/>
<input type="submit" value="Delete Review" />
</form>
</body>
</html>
<?php
}
}
GetReview($_POST['BookTitle'])
However, it leads me to the next form with nothing in the input text and this warning:
Warning: mysql_fetch_row(): supplied argument is not a valid MySQL result resource in C:\AppServ\www\GetReview.php on line 20
I've searched and tried different code but still same result.
Could anyone please tell me where the error is???... Thanks
$qq = mysql_query($q,$con);
if(!$qq) {
// (...)
$row = mysql_fetch_row($qq);
I'm not going to be a lot of help, but your question seems to be where the error is occuring, and I can tell you that.
It's in the $row = mysql_fetch_row($q); line.
You can tell this because the error record starts with mysql_fetch_row(), and the above line is the only mention of mysql_fetch_row() in the code.
Check the SQL query by printing the output of $q variable with:
echo $q;
Now, try to execute it from your MySQL client. Collect the results (if there are) and check for errors.
A suggestion: If you want, you can use a tool like ezSQL that can be very useful (especially for code organization)

Two Search Fields (One a drop down list) - PHP & MYSQL Code

I really would like some help on this as I'm pulling hair out!!!
I have two fields, one being an input box & the other being a drop down list which search the database and display the results, however I cannot seem to figure it out...here is what I have so far...
This is the actual search form:
<form id="myform" name="myform" action="<?php echo $_SERVER['PHP_SELF']?>" method="get"><br />
<div class="T1"><br /><p></div> <input name="term" type="text" value="<? php echo $_GET['searched']; ?>" size="10" maxlength="4" placeholder="e.g. BS1"/>
<select>
<option value="">I feel like...</option>
<option value="">Anything</option>
<option value="Indian">Indian</option>
<option value="Chinese">Chinese</option>
<option value="Thai">Thai</option>
</select>
<input type="submit" name="submit" value="Go"/>
</form>
And this is the PHP code:
<?php
if (isset($_GET['submit'])){
mysql_connect ("host", "user","password") or die (mysql_error());
mysql_select_db ("database");
$term = $_GET['term'];
$term = $_GET['option value'];
}
else
$sql = mysql_query("select pagetitle from Restaurant where extra like '%$term%' and showing like '1'");
$sql = mysql_query("select cuisine from Restaurant where cuisine like 'option value' and showing like '1'");
echo Restaurants in $term and Cuisine $option value:";
}
while ($row = #mysql_fetch_array($sql)){
echo ''.$row['pagetitle'];
echo '<br/>';
}
}
?>
The database has a table called Restaurant with two coloumns, one called 'Extra' which contains the postcode & the other called 'Cuisine' which containts the cuisine.
I would like it to return a list of restaurants that match both 'Extra' and 'Cuisine'
Any help will be greatly appretiated.
Echoing $_SERVER['PHP_SELF'] or $_GET['searched'] anywhere in your script (even in the form action) will open your site up to XSS attacks. Do not do this unless you sanitize them first.
For all new projects, it is recommended to use prepared statements for mysql queries. You can do this with either mysqli or PDO. Your code is just asking for SQL injection by the looks of what you are trying to do.
You are missing a bracket in your code and you have some extra ones at the end. Also after echo you're missing a quotation mark. I'm not sure what's going on there. Try to get those fixed.
What is with the # before mysql_fetch_array() ? There are really very few cases where # should ever be used in PHP. It is usually an indicator that there is some sort of error somewhere in your code that should be fixed instead of suppressed.
Your needs a name attribute if you want to be able to use it in PHP.
In your SQL query, you should not be using LIKE when you should be using equals. Also, you should not quote integers.
Why are you echoing an empty string like echo ''.$somevar; ? Just echo the variable.
I'm not sure what "showing" is for but I assume is a record that can be displayed. The first thing to do is update your query:
$sql = mysql_query("select pagetitle, cuisine from Restaurant where (extra like '%$term%') and (showing like '1') and (cuisine like 'option value')");
You also need to check if the user did not enter an option or selected 'anything' in which case the query needs to be changed a little:
$sql = mysql_query("select pagetitle, cuisine from Restaurant where (extra like '%$term%') and (showing like '1') and (cuisine like 'option value' or 'option value' = '')");

Categories