Making a search engine using PDO/PHP - 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.

Related

Styling output of database from php loop

I'm trying to display data from database and it is important to me that this output is placed on different sides of website. I used php to connect to database, and ajax jquery to refresh data because every 20second values change.
I tried to
echo <div styles='position: absolute; top: 0px' class='text'>{$row['id']}</div>
in a foreach loop but when I do this all 6 of my id's are stacked on top each other.
Making <div> outside loop was unsuccessful too. I guess my problem is in reading data from database because I read all at once but I don't know any other way to do this except wrtiting 6 connection files to gather only the one value that I want to display and then styling it, but I feel like there is smarter way of doing this.
This is my code. Just want to say this is my first contact with php.
<?php
$hostname = "someinfo";
$username = "someinfo";
$password = "someinfo";
$db = "someinfo";
$dbconnect = mysqli_connect($hostname,$username, $password,$db) or die("cant");
if ($dbconnect->connect_error) {
die("Database connection failed: " . $dbconnect->connect_error);
}
$sensor_names = array();
$query2 = mysqli_query($dbconnect,"show tables");
while($row2 = mysqli_fetch_array($query2)){
if($row2[0] == 'sensors' or $row2[0] == 'measurments'){
break;
}
else{
array_push($sensor_names,$row2[0]);
}
}
$query = mysqli_query($dbconnect, "select s.id, s.sensor_name, max(dev.id), dev.temprature, dev.date from sensors s, `{$sensor_names[0]}` dev where s.id=dev.sensor_id gro
up by s.id, s.sensor_name order by s.id asc");
while($row = mysqli_fetch_array($query)){ //i konw this is ugly but this is working placeholder
foreach($sensor_names as $sn){
$query = mysqli_query($dbconnect, "select s.id, s.sensor_name, dev.temprature, dev.date from sensors s, `{$sn}` dev where s.id=dev.sensor_id order by dev.id desc limit 1");
$row = mysqli_fetch_array($query);
echo "
{$row['id']}
{$row['sensor_name']}
{$row['temprature']}
{$row['date']}
<br>";
}
}
?>
This is off-the-cuff from a guy who hasn't touched PHP in a long while, so watch for major bugs. But the basic idea is like this: build the code in a variable, and when done, echo out the entire variable. Makes it easier to add the structure/formatting you want. Note that you can also stick in a style tag along with that code and blurp out the style along with the "table" (Personally, I wouldn't use a table for styling, this is just for demo).
Note: I didn't style the output so that it puts the data on either side of the page - I left that for you to do. It's basic HTML - divs, styles, maybe css grid or flexbox. The point is to create your CSS/HTML/PHP mashup in a string variable and output the entire thing when done.
$out = '<style>.cell_id{font-weight:bold;}</style>';
$out .= '<table><tr><th>Label 1</th><th>Label 2</th><th>Etc</th></tr>'; //<=== ADDED!
while($row = mysqli_fetch_array($query)){
foreach($sensor_names as $sn){
$query = mysqli_query($dbconnect, etc. etc. etc.);
$row = mysqli_fetch_array($query);
$out .= "
<tr>
<td class='cell_id'>{$row['id']}</td>
<td>{$row['sensor_name']}</td>
<td>{$row['temprature']}</td>
<td>{$row['date']}</td>
</tr>";
}
}
echo $out;
Ok I think I got it. Cssyphus's answer got me thinking and I wrote something like that array_push($data, $row) and $data is two dimentional array that hold all data I need and now I can style it easily.

Creating a search engine of your site [closed]

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

PHP output as link from database

I have the following code that works by outputting as a link ( the link comes from a field in my database) I wish to do the same for the code below, however i cannot get it work, here is the example of what I have that works, and the code that i wish to make output as a link:
Working Code what I want it to look like
if (!empty($_REQUEST['term'])) {
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM adrenaline WHERE title LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo '<br> '. $row['title'] .'';
}
}
?>
And the code that i have at the moment, it works by be manually typing in the hyper link, however I wish to make it take the link from the database like the example above
//query the database
$query = mysql_query("SELECT * FROM hobby WHERE id = '1' ");
//ferch the results / convert results into an array
WHILE($rows = mysql_fetch_array($query)):
$title = $rows['title'];
echo "<a href='shard.php'>$title</a>";
endwhile;
?>
Many thanks!
I am not 100% certain if this is what you meant to ask... let me know in comments:
<?PHP
$query = mysql_query("SELECT * FROM hobby WHERE id = '1' ");
if(mysql_num_rows($query) >= 1) {
while($rows = mysql_fetch_array($query)) {
echo sprintf("%s", $rows["description"], $rows["title"]);
}
} else { echo "No hobbies found."; }
?>
I believe you might have faced some syntax issues while dealing with quotes parsing a variable in <a html tag. Consider using sprintf something like in my example.
I have also added a mysql_num_rows() just in case and you can see its a good fail-safe method incase there are no rews found on any select query.
IMPORTANT: STOP using mysql_ functions because its deprecated from new PHP versions. Use PDO or mysqli instead.

How do i get downline of userid in a table with mysql

Currently i'm using php and mysql to fetch downlines of a particular userid. Is there any way i can just use mysql to do that. My code is......
function downlineSearch($mid, $s)
{
global $nums; global $str;
$q = $cn->query("SELECT userid, CONCAT(lastname,' ',firstname,' ',middlename) AS name FROM clientsdata WHERE (recid LIKE '%$s%' OR lastname LIKE '%$s%' OR firstname LIKE '%$s%' OR middlename LIKE '%$s%') AND sponsor = $mid");
while($r = $q->fetch_array(MYSQL_ASSOC))
{
$nums += 1;
$str .= "<tr><td valign='middle'>NRN".$r['userid']."CCN</td><td valign='middle'>".$r['name']."</td></tr>";
downlineSearch($r['userid'], $s);
}
}
$str = '';
downlineSearch($mid, 'janet');
echo '<table id="tblSearch" width="100%">';
echo "<tr><td colspan='4' align='center' style='padding-top:10px;'><h3> $nums records found for [ <span style='color:red'>".$_POST['s']."</span> ]</h3></td></tr>";
echo $str;
echo '</table>';`
PLEASE ANY HELP WOULD BE HIGHLY APPRECIATED. THANKS
My guess it that you need to set the value of $cn, probably something like that:
$cn = new mysqli;
Does that help?
What is the error message you are getting?
Do you know in which line the error happens?
Do you have ability to debug line-by-line and view variables? If not, add several "echo" statements, to view in browser what's going on. Or, use error_log(), to display info in PHP error log, if you have access to it.
(I'm sorry about asking for clarification in an "answer", but the system does not let me add comments to other people's question - yet. As soon as you add some clarification, I will revise this "answer" to be actual answer to your question.)

PHP MYSQL each letter is link to another movie but when i click i get all movies

When I click on any link it opens all movies in my database. I want only that movie which begins with that letter and I don't know where I've made a mistake. Here is my code:
$azRange = range('A', 'Z');
foreach ($azRange as $letter){
echo ''.$letter.' | ';
}
if(isset($_GET["task"]) && $_GET["task"] == "view"){
$naslov = $_GET['naslov'];
$query = "SELECT filmovi.naslov, filmovi.godina, filmovi.trajanje, filmovi.slika
FROM filmovi
ORDER BY naslov";
$result = mysql_query($query)
or die ('SQL Greska: '.mysql_error());
if($result){
while($filmovi = mysql_fetch_array($result)){
echo '<center><b>';
echo '<td><img src="img/'.$filmovi["slika"].'" border="0" width="100" /></td>';
echo '</br>';
echo '<td>'.$filmovi["naslov"].'</td>';
echo '<td> ('.$filmovi["godina"].')</td>';
echo '<br>';
echo '<td>Trajanje: '.$filmovi["trajanje"].' min</td>';
echo '</b></center>';
echo '</tr>';
}
You are not passing the letter to the database query at any point.
$query =
"SELECT filmovi.naslov, filmovi.godina, filmovi.trajanje, filmovi.slika
FROM filmovi
WHERE naslov LIKE '$naslov%'
ORDER BY naslov";
Your query
$query = "SELECT filmovi.naslov, filmovi.godina, filmovi.trajanje, filmovi.slika
FROM filmovi
ORDER BY naslov";
is fetching all the movies from the database. There is no filtering here. Add some where conditions to this query and you'll get the expected result.
Changing to this query might help:
SELECT filmovi.naslov, filmovi.godina, filmovi.trajanje, filmovi.slika
FROM filmovi
WHERE `naslov` LIKE '{$naslov}%'
ORDER BY naslov
Since others have already answered your question (missing WHERE clause), I just want to mention that the <center> HTML tag is deprecated, and you should use CSS instead.
The mysql driver for PHP is also outdated, so instead of using:
mysql_query($query);
you should use
mysqli_query($link, $query);
for better security, OOP support, prepared statements, and transactions.
You can read about it here
Even if you are a beginner and you don't care about what those features mean, you should try and get into the habit of using mysqli anyway, so that when the day comes that you learn to appreciate it, you don't have to go back and update all of your code.

Categories