Creating a search engine of your site [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Am a student and novice to the domain of PHP (I have no idea on it). I have assigned a small task of creating a search engine of the website. (I have edited my code based on suggestions)
I have written the following code by searching the google and various forums.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.W3.org/TR/xhtml/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Results </title>
</head>
<body>
<center>
<h1 style="color:#09F; font-size:36px;"> Search </h1>
<form action="./results.php" method="get">
<input type="text" name="input" size="50" value='<?php echo $_GET ['input'];?>' />
<input type="submit" value="search" />
</form>
</center>
<hr/>
<?php
$input = $_GET['input'];
$terms = explode(" ", $input);
$query = "SELECT * FROM search WHERE ";
$first = true;
foreach ($terms as $each) {
if ($first) {
$query .= "keywords LIKE '%$each%' ";
$first = false;
}
else {
$query .= "OR keyword LIKE '%$each%' ";
}
}
//Connect to Database
mysql_connect("localhost","root","");
mysql_select_db("databasem") or die ("database not found");
$query = mysql_query($query);
$numrows = mysql_num_rows($query) or die ("Here's the error");
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</a></h2>
$description<br/><br/>";
}
}
**else
echo "No result found for \"<b>$input</b>\"";**
//Disconnect
mysql_close();
?>
</body>
</html>
Am getting the error in line where it is marked bold. mysql is showing that the query is wrong.
I searched google and I found the answers that PHP is using Mysqli instead of Mysql.
I have no idea on it. I found some materials and I was unable to understand it.
It seems to be a silly/useless question for you (experts) but as per my standards and experience this problem hurts me a lot.
---------------------------(Here Comes the points after updating the code)------------
After updating the code everything is going fine when searching but the last else Statement is not runnning. When we searches for the Name which is not located it is not displaying any results instead of displaying "No results found for $Input string".
Can anyone guide me over here please
Thanks

Main problems:
1) Bad variable:
$query .= "keywords LIKE '%each%' ";
^---missing $
since there's no $, you're searching for the literal characters e, a, c, h.
2) Assuming your query can never fail:
$query = mysql_query($query);
^---no error handling
You check for failure on connection and the num_rows call, but not on the most important part: the actual query. Try
$query = mysql_query($query) or die(mysql_error());
3) Vulnerable to sql injection attacks
4) Using the obsolete/deprecated mysql_*() function library.

Your error is in the foreach part, you never increment the $i, so it stays at 0.
This will make the query incorrect because it always picks the if part and not the else part
You also define the $i in the foreach so it will get created each time. It should be on the outside and on the inside of the loop should be $i++ (to increment the $i)
Syntax
$first = true;
foreach ($terms as $each) {
if ($first) {
$query .= "keywords LIKE '%$each%' ";
$first = false;
}
else {
$query .= "OR keyword LIKE '%$each%' ";
}
}
Using mysql is deprecated in current versions of php so you should upgrade to mysqli or PDO where you can also use prepared statements for preventing sql injection.
But maybe that is not necessary for your school project

Related

PHP script free of syntax errors won't fully parse [duplicate]

This question already has answers here:
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Closed 4 years ago.
I have been struggling with this PHP script on my personal web server for quite some time. No matter what I do, or what input I give the HTML form (this PHP script is the action page for that form), I end up with a page that looks like this:
view larger version
Below is my code, which is supposed to get a list of ids of the recipes with a tag matching the user's query, then display a quick overview of the matching recipes to the user, in table format:
<html>
<body>
<title>Recipe Database</title>
<h1>recipe finder</h1>
</body>
</html>
<?
$servername = "localhost";
$username = "root";
$password = "xxxx";
$con = mysqli_connect($servername, $username, $password, "recipes");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$tag = $_POST["keyword"];
$query = mysqli_query($con, "SELECT id FROM recipes WHERE tag1 LIKE '$tag'");
$query2 = mysqli_query($con, "SELECT id FROM recipes WHERE tag2 LIKE
'$tag'");
$query3 = mysqli_query($con, "SELECT id FROM recipes WHERE tag3 LIKE'$tag'");
$result = mysqli_fetch_array($query);
$result2 = mysqli_fetch_array($query2);
$result3 = mysqli_fetch_array($query3);
$list = array_merge($result, $result2);
$list = array_merge($list, $result3);
if ($list[0] != ""){
echo "<table>";
for ($i = 0; $i < count($list); $i++) {
echo "<tr>";
$detailquery = mysqli_query($con, "SELECT * FROM recipes WHERE id LIKE
\"$list[$i]\"");
$details = mysqli_fetch_array($detailquery);
print "<h3>" . $details[1] . "</h3>";
print "<p>" . $details[2] . " minutes</p>";
print "<p>" . $details[3] . " servings</p>";
echo "</tr>";
}
echo "</table>";
} else {
echo "No recipe with that tag was found. Try a different tag.";
}
?>
I tested it on several different online syntax checkers and it came out clean. Yes, all other PHP scripts are running fine on my server. Yes, all the other PHP scripts are reading and writing to this database and others on my server without error. Yes, I did try wrapping body and html around the PHP script, it makes no difference. Yes, I have checked for unpaired quotation marks and apostrophes, there are none. Yes, I have tried storing the various queries in separate variables, that did not affect anything.
Any help would be appreciated, I am truly stuck on this one. Thank you!
Oops, it looks like I forgot to have the extended tag
<?php
instead of the short one without "php". My bad for being so oblivious.

WHERE clause effecting SQL query

I am trying to make this program where I can delete a thread if I am logged in. Now I already have the button linked and everything, I have it doing multiple tasks when pressed, but it seems to not run the SQL query I want it to. Now I have a variable called $forumid which is set in the URL and retrieved using $_GET['forumid'];
I know this is setting properly, because I have done echo $forumid; and its been correct. But there is one line of code that doesn't run for some reason, and that is:
$db->query("DELETE FROM threads WHERE id='$forumid'");
Now when I remove the WHERE clause, it works, but it wipes out the entire table. So I now know that the problem is the WHERE clause, I just can't find out why it is the issue. I am fairly new to PHP so please forgive my ignorance. But if anyone is able to see the issue, please tell me. Thank you.
[EDIT: COMPLETE CODE]
<?php
require 'connect.php';
session_start();
$forumid = $_GET['forumid'];
$title;
$body;
$by;
$loggedAsAuthor;
?>
<html>
<head>
<title>Legend Factions - View Forum</title>
<link href="stylesheet.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="header">
Home
Forum
Vote
Donate
Members
</div>
<div id="content">
<div id="divider">
<?php
if ($result = $db->query("SELECT * FROM threads")) {
while ($row = $result->fetch_assoc()) {
if ($row['id'] == $forumid) {
$title = $row['title'];
$body = $row['words'];
$by = $row['by'];
if ($_SESSION['sess_username'] == $by || $_SESSION['sess_username'] == "admin") {
$loggedAsAuthor = true;
}
}
}
}
echo '<h2>', $title, '</h2><br/><label>By: ', $by;
if (isset($loggedAsAuthor)) {
echo '<form action="viewForum.php" method="post">
<br/><input type="submit" name="delete" value="Delete Thread"/>
</form>';
}
$delete = $_POST['delete'];
if (isset($delete)) {
$db->query("DELETE FROM threads WHERE id=$forumid ");
//header("Location: forum.php");
}
?>
<hr/>
<?php
echo $body;
?>
</div>
</div>
</body>
</html>`
You need to modify your sql query as like :
$db->query("DELETE FROM threads WHERE id= $forumid "); // removed single quotes
Hope it works for you now.
You can try this way, Hope it will help
$qry = "DELETE FROM threads WHERE id= $forumid ";
$db->query($qry);
Your query seems to be correct.
If $_GET['forumid'] is a string, do :
$db->query("DELETE FROM threads WHERE id=".$db->quote($_GET['forumid']));
If $_GET['forumid'] is numeric, do :
$db->query("DELETE FROM threads WHERE id=".(int)$_GET['forumid']);
In any case, string syntax should work, because string will be cast to integer by mysql.
To debug, do :
echo "DELETE FROM threads WHERE id=".$db->quote($_GET['forumid']) ;
And give us the result, or directly paste it into phpMyAdmin to see the error.
You should also add this line at the top of your script to see all errors :
error_reporting(E_ALL) ;
ini_set('display_errors', true) ;
if(isset($_GET['forumid']) && !empty($_GET['forumid'])){
$qry = "DELETE FROM threads WHERE id= '" . mysql_real_escape_string ($_GET['forumid']) . "'";
}
or use active record
$this->db->where('id', $forumid );
$this->db->delete('threads ');
Either integer or string syntax in MySQL should work if the threads id is an integer. What I see that could be happening is:
1) $forumid does not have the value you think it has?
To check it, var_dump the variable right before the delete query:
var_dump($forumid); die;
2) The table id column is not named "id"?
Check the database schema, to check if the column has the name you think it should have. In mysql CLI:
desc threads;

mysql php search engine query multiple columns

So i am currently messing around creating a search engine just out of interest and was curious if i was able to query more than just the keyword column in the mysql database. At the moment i am able to search for somthing and get the results based off of my "keyword" column. But if the word or phrase i am searching not within the keyword column but it is found in the title column or description column is it possible for it to show up because it found it within those columns aswell?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Search Engine - Search</title>
</head>
<body>
<h2>Search Engine</h2>
<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 databeast WHERE ";
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "keywords LIKE '%$each%' ";
else
$query .= "OR keywords LIKE '%$each%' ";
}
//connect
mysql_connect("localhost", "username", "password");
mysql_select_db("fapster") or die(mysql_error());
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)){
$url = $row['url'];
$title = $row['title'];
$keywords = $row['keywords'];
echo "<h1><a href='$url'>$title</a></h1>
$keywords<br /><br />";
}
}
?>
</body>
</html>
Thanks in advance
I suggest you check into MySQL Full-Text search. http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html.
This allows you to search multiple keywords in a query. Plus, Full-Text gives you the benefit of actually understanding the words as "natural language" (so it deals with "stop words", "plurals" and "word stemming"). See http://dev.mysql.com/doc/refman/5.0/en/fulltext-query-expansion.html
Don't throw out the "Like" logic. MySQL Full-Text search has a few annoying things - so you may still want to use that logic. Here they are:
Searches which return "too many" (%50 or greater) results return nothing. Not what a searcher usually expects, right? Normally people want it to work like Google does.
Searches on words which are too short return nothing (see ft_min_word_len in /etc/my.sql)
Usually I combine the full text search with the like or "or" search and then ORDER by full text rank.
p.s. you'r script is vulnerable with SQL injection. Don't release onto Internet before reviewing.

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.

Dynamic url or pages in php

Well it's been my very first initiative to build a dynamic page in php. As i'm a newbie in php, i don't know much about php programming. i've made a database named "dynamic" and it's table name "answer" after that i've inserted four fields namely 'id', 'A1','A2', 'A3'.
I inserted the value in id=1 which are A1=1,A2 and A3-0,
In id=2, i have inserted A1=0, A2=1, A3=0
In id-3, i have inserted A1 and A2=0 A3=1
So now what i wanted is whenever i will click on the link of id=1 then it will display the content of id=1 and so on...
What i've done so far are:-
$conn= mysql_connect("localhost","root", "");
$db= mysql_select_db("dynamic", $conn);
$id=$_GET['id'];
$sql= "select * from answer order by id";
$query= mysql_query($sql);
while($row=mysql_fetch_array($query, MYSQL_ASSOC))
{
echo "<a href='dynamic.php?lc_URL=".$row['id']."'>Click Here</a>";
if($row['A1']==1)
{
echo "A1 is 1";
}
else if($row['A2']==1)
{
echo "A2 is 1";
}
else if($row['A3']==1)
{
echo "A3 is 1";
}
else {
echo "Wrong query";
}
}
?>
When i've executed this codes then it is showing me the exact id and it is going to the exact id but the values has not been changing..
I want whenever i will click on the id then it will display the exact value like if i click on id=2 then it will echo out "A2 is 1" nothing else....
Can anyone please help me out?
I also have noticed about
$id=$_GET['id'];
what is it and how to use it. Can anyone explain me out..
Thanks alot in advance:)
It may be best to start here to get a good understanding of php, before diving so deep. But to answer the specific questions you asked here...
The php $_GET variable is defined pretty well here:
In PHP, the predefined $_GET variable is used to collect values in a
form with method="get".
What this means is that any parameters passed via the query string (on a GET request) in the URL will be accessible through the $_GET variable in php. For example, a request for dynamic.php?id=1 would allow you to access the id by $_GET['id'].
From this we can derive a simple solution. In the following solution we use the same php page to show the list of items from the answer table in your database or single row if the id parameter is passed as part of the url.
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$mysqli = new mysqli("localhost", "user", "password", "dynamic");
$query = 'SELECT * FROM answer';
if ($_GET['id']) {
$query .= ' WHERE id = '.$_GET['id'];
} else {
$query .= ' ORDER BY id';
}
$res = $mysqli->query($query);
if ($res->num_rows == 0) {
echo '<p>No Results</p>';
} else if ($res->num_rows == 1) {
// Display Answer
$row = $res->fetch_assoc();
echo '<h3>Answer for '.$row['id'].'</h3>';
echo '<ul>';
echo '<li>A1 = '.$row['A1'].'</li>';
echo '<li>A2 = '.$row['A2'].'</li>';
echo '<li>A3 = '.$row['A3'].'</li>';
echo '</ul>';
} else {
// Display List
echo '<ul>';
while ($row = $res->fetch_assoc()) {
echo '<li>Answers for '.$row['id'].'</li>';
}
echo '</ul>';
}
?>
</body>
</html>
OK, this might not be exactly what you are looking for, but it should help you gain a little better understanding of how things work. If we add a little javascript to our page then we can show/hide the answers without using the GET parameters and the extra page request.
<!DOCTYPE HTML>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<?php
$mysqli = new mysqli("localhost", "user", "password", "dynamic");
$query = 'SELECT * FROM answer ORDER BY id';
$res = $mysqli->query($query);
if ($res->num_rows == 0) {
echo '<p>No Results</p>';
} else {
// Display List
echo '<ul>';
while ($row = $res->fetch_assoc()) {
echo '<li>Answers for '.$row['id'].'';
echo '<ul id="answers_'.$row['id'].'" style="display:none;">';
echo '<li>A1 = '.$row['A1'].'</li>';
echo '<li>A2 = '.$row['A2'].'</li>';
echo '<li>A3 = '.$row['A3'].'</li>';
echo '</ul>';
echo '</li>';
}
echo '</ul>';
}
?>
<script>
function toggleAnswers(answer) {
$('#answers_' + answer).toggle();
}
</script>
</body>
</html>
There are many more solutions, each more complicated that what I've presented here. For example we could set up an ajax request to load the answers into the list page only when an item is clicked. My advice is to go through some beginner tutorials on php and look at some of the popular PHP frameworks: Zend, CodeIgniter, CakePHP, etc. Depending on what you overall goal is, one of these might really help you get there faster.
Be warned that the code provided here is only an example of how to accomplish what you were asking. It definitely does not follow all (if any) best practices.

Categories