This question already exists:
Closed 10 years ago.
Possible Duplicate:
how to have ranking based on how many words match user input
How can I have a search engine ranked by amount of words that are typed in and ranked by the amount of types they crop up in the fields title, description, keywords, link.
So the higher results are ordered by having more of the words that the user submitted. Say if the user typed in iPhone, iPhone key word crops up in the link, description and title field, so that would be ranked higher than say Apple which mentions it only in the description and Apple Store which mentions it in the title and the description.
My code is below:
$query = " SELECT * FROM scan WHERE ";
$terms = array_map('mysql_real_escape_string', $terms);
$i = 0;
foreach ($terms as $each) {
if ($i++ !== 0){
$query .= " AND ";
}
$query .= "Match(title, description, keywords, link) Against ('".implode(' ',$terms)." IN BOOLEAN MODE') ";
}
$secs = microtime();
$query = mysql_query($query) or die('MySQL Query Error: ' . mysql_error( $connect ));
echo '<p class="time">Qlick showed your results in ' . number_format($secs,2) . ' seconds.</p>';
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$title1 = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
$rank = $row['rank'];
$title = substr($title1,0,60);
echo '<h2><a class="ok" href="' . $link . '">' . $title . '</a></h2>' . PHP_EOL;
echo '<p class="kk">' . $description . '<br><br><span class="keywords">' . PHP_EOL;
echo '<p><a class="okay" href="' . $link . '">' . $link . '<br><br><span class="keywords">' . PHP_EOL;
}
While I'm sure it is possible to implement this within mysql, a full-text search index like solr/lucene is designed to handle this stuff directly. You might find better resources & help going down that road.
Using php, copy the array returned by the mysql query:
while ($row = mysql_fetch_assoc($query))
{
$rows[] = $row;
}
Then you can loop over $rows and assign a score to
foreach ($rows as $row)
$row['score'] = score_row($row, $terms)
score_row is a helper method that returns a bigger score depending on which columns have which terms and your definition of "importance".
Then sort thw rows by score, then print the results as you were doing.
Related
I have been tasked with presenting a list of all photographs in relation to a photographer, when that photographer is clicked. I need to echo the list of photographs but currently, only the last row is being echoed.
The rows returned should look like this (minus the bullet points):
1 Amager Standpark Sunset 2010-07-01 _img/1/1.jpg 1
1 Field Landscape 2010-07-09 _img/1/2.jpg 1
However my code is only returning this:
1 Field Landscape 2010-07-09 _img/1/2.jpg 1
Below is my code:
// SQL query to get all photo data from specific photographer
$query = mysqli_query($con, "SELECT * FROM Photograph WHERE PhotographerId='$photographerID'");
$photos = mysqli_fetch_assoc($query);
$num = mysqli_num_rows($query);
if ($num == 0) {
echo 'This are no photographs present for this photographer.';
} else if ($num > 0) {
$list = '';
while ($photos = mysqli_fetch_array($query)) {
$list .= $photos['PhotographerId'] . ' ' . $photos['PhotographName'] . ' ' .
$photos['Date'] . ' ' . $photos['PhotographURL'] . ' ' .
$photos['Visible'] . ' </br>';
}
echo $list;
}
You're calling mysqli_fetch_assoc() right after you run your query effectively using the first set of results. Then once you start your loop you start t=at the second row.
Removing it will solve your issue and make the first result set available to your loop.
You can also just use mysqli_fetch_assoc() instead of mysqli_fetch_array() inside of your loop. mysqli_fetch_array() returns both the associative and numerically indexed results of your query which you don't need.
// SQL query to get all photo data from specific photographer
$query = mysqli_query($con, "SELECT * FROM Photograph WHERE PhotographerId='$photographerID'");
$num = mysqli_num_rows($query);
if ($num == 0) {
echo 'This are no photographs present for this photographer.';
} else if ($num > 0) {
$list = '';
while ($photos = mysqli_fetch_assoc($query)) {
$list .= $photos['PhotographerId'] . ' ' . $photos['PhotographName'] . ' ' .
$photos['Date'] . ' ' . $photos['PhotographURL'] . ' ' .
$photos['Visible'] . ' </br>';
}
echo $list;
}
I don't know where you get $photographerID from but if it is user input this code is vulnerable to SQL Injection Attacks. You should consider using prepared parameterized statements to avoid this risk.
include "connection file";
$query = "SELECT * FROM Blog";
$result = mysqli_query($query);
$num_results = mysqli_num_rows($result);
for($i=0; $i<$num_results; $i++) {
$row = mysqli_fetch_assoc($result);
echo "<div class="blogEntry"><h4>" . $row['title'] . "</h4><h5>" . $row['date'] . "</h5><p>"
. $row['text'] . "</p></div>";
}
Hi, so, I'm trying to loop through all my blog posts and display them to the page in order so the newest entry is first but I can't seem to get it too work. tried a few different ways and always white screen! Any help would really be appreciated :). I'm also going to add a search function and filters, I don't need this now but any suggestions where to look to find info about implementing these would also be really helpful. Link to where I'm putting this code on my website: http://www.obeytoplay.com/. Thanks!
tried a few different ways and always white screen!
That's because there's a syntax error in your code. Either escape the inner double quotes(") using backslash(\) or use single quotes(').
Method(1):
include "connection file";
$query = "SELECT * FROM Blog";
$result = mysqli_query($query);
$num_results = mysqli_num_rows($result);
for($i=0; $i<$num_results; $i++) {
$row = mysqli_fetch_assoc($result);
echo "<div class=\"blogEntry\"><h4>" . $row['title'] . "</h4><h5>" . $row['date'] . "</h5><p>" . $row['text'] . "</p></div>";
}
Method(2):
include "connection file";
$query = "SELECT * FROM Blog";
$result = mysqli_query($query);
$num_results = mysqli_num_rows($result);
for($i=0; $i<$num_results; $i++) {
$row = mysqli_fetch_assoc($result);
echo "<div class='blogEntry'><h4>" . $row['title'] . "</h4><h5>" . $row['date'] . "</h5><p>" . $row['text'] . "</p></div>";
}
I'm trying to loop through all my blog posts and display them to the page in order so the newest entry is first
Use ORDER BY in conjunction with SELECT clause to reorder the result set, like this:
SELECT * FROM Blog ORDER BY column_name DESC/ASC;
Here's the reference:
ORDER BY
everyone. I'm having a bit of a PHP conundrum here and I couldn't find a good answer that already existed. You see, I'm working on a project where I have to take a classmate's discography website and revamp it with PHP, to where, instead of having the album covers and tracklists hard-coded in, it would query the database for them. My problem is that I have to keep the general style of his site intact, and I'm having trouble doing that. Basically his styles depend on having the album cover, name, and tracklists in div tags, and the style he's got in place is achieved through both Bootstrap and his own, custom CSS stylesheet.
Before I start to ramble, my question is: is there any way to wrap looping output in HTML tags? I need to get the album cover, album name, and tracklists in a div tag, but only the tracklists loop. Here is the code I have in place to query the database:
<?php
require ('mysqli_connect.php');
// Connect to database server
mysql_connect("localhost", "admin", "instructor") or die(mysql_error());
// Select database
mysql_select_db("phprediscography") or die(mysql_error());
// SQL query
$q = "SELECT DISTINCT albums.albumname, albums.albumID, albums.coverart
FROM albums
JOIN tracks
ON albums.albumID=tracks.albumID"; //select UNIQUE results from database
$t = "SELECT trackname FROM tracks WHERE albumID = 1";
$b = "SELECT trackname FROM tracks WHERE albumID = 2";
$n = "SELECT trackname FROM tracks WHERE albumID = 3";
$r = "SELECT trackname FROM tracks WHERE albumID = 4";
$result = mysqli_query($dbcon, $q);
$result1 = mysqli_query($dbcon, $t);
$result2 = mysqli_query($dbcon, $b);
$result3 = mysqli_query($dbcon, $n);
$result4 = mysqli_query($dbcon, $r);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { //loop through database to get each album
echo '<img class="img-responsive" src=' . $row['coverart'] . '>' . '<br />';
echo '<h2>' . $row['albumname'] . "</h2><br />";
if ($row['albumID'] == 1) {
foreach($result1 as $row1) { //loop through tracks and output to page
echo '<p>' . $row1['trackname'] . '</p>';
}
}
if ($row['albumID'] == 2) {
foreach($result2 as $row2) { //loop through tracks and output to page
echo '<p>' . $row2['trackname'] . '</p>';
}
}
if ($row['albumID'] == 3) {
foreach($result3 as $row3) { //loop through tracks and output to page
echo '<p>' . $row3['trackname'] . '</p>';
}
}
if ($row['albumID'] == 4) {
foreach($result4 as $row4) { //loop through tracks and output to page
echo '<p>' . $row4['trackname'] . '</p>';
}
}
}
// Close the database connection
mysql_close();
?>
If I need to post anything else, let me know, this is my first-ever question so I'm just kind of feeling it out.
By doing your $t = "SELECT trackname FROM tracks WHERE albumID = #"; and if($row['albumID']==#) you are essentially still hardcoding similar to your friend. Just do 1 query, where you join all the tracks. Then when looping, group by the albumname -
<?php
require('mysqli_connect.php');
// SQL query
$q = "SELECT albums.albumname, albums.albumID, albums.coverart, tracks.trackname
FROM albums
JOIN tracks
ON albums.albumID=tracks.albumID";
$result = mysqli_query($dbcon, $q);
$current_albumID = ""; //create current albumID var to be used below.
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){//loop through database to get each album
if($row['albumID'] != $current_albumID){
echo '<img class="img-responsive" src='.$row['coverart'] . '>' . '<br />';
echo '<h2>' . $row['albumname'] . "</h2><br />";
$current_albumID = $row['albumID']; // set current albumID to this albumID
}
echo '<p>' . $row['trackname'] . '</p>';
}
?>
Try something like this instead: Get all the data you're after in your first query, then use php to process that into your output:
$q = "SELECT albums.albumname, albums.albumID, albums.coverart, tracks.trackname
FROM albums
JOIN tracks ON albums.albumID=tracks.albumID";
$result = mysqli_query($dbcon, $q);
$lastAlbumId = null;
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
if ($lastAlbumId != $row['albumID']) {
echo '<img class="img-responsive" src="'.htmlentities($row['coverart']).'"><br />';
echo '<h2>'.htmlentities($row['albumname']).'</h2><br />';
}
echo '<p>'.htmlentities($trackname).'</p>';
$lastAlbumId = $row['albumID'];
}
A few things to note:
I added use of htmlentities to escape the user data so malicious people can't type in HTML somewhere and have it appear on your site. This is something you should do almost everywhere you're displaying data from a database in a html site, except for very rare cases where you know what you're doing.
You probably don't need those <br /> tags - <h2> is a block level element so it'll force itself onto it's own line anyway (unless there's some silly CSS rules somewhere).
Also note - the above code is untested - typed straight into browser. There may be some syntax errors - let me know if you see any problem and I'll happily edit the answer. (or you can suggest an edit).
I have written a calendar implementation, which is working, but displays only one set of data, I'm trying to make it appear all of the data in my select query:
$events = '';
$query = mysql_query('SELECT event_id, event_type, time, date, location, home_or_away, team_id FROM event WHERE date = "'.$deets.'"');
$num_rows = mysql_num_rows($query);
if($num_rows > 0) {
$events .= '<div id="eventsControl"><button onMouseDown="overlay()">Close</button><br /><br /><b> ' . $deets . '</b><br /><br /></div>';
while($row = mysql_fetch_array($query)){
I know it has to do with something with this, but I don't know exactly what code to imply to get 'event_type', 'time' and etc
$desc = $row['event_id'] ;
$events .= '<div id="eventsBody">' . $desc . '<br /> <hr><br /></div>';
}
}
echo $events;
?>
You can use your columns as keys in the array. So to have time, use $row['time'] and so on.
For showing multiple data, try concatenating
$desc = $row['time'] .$row['event_type']
You mean something like
$time = $row['time']
etc?
I'm not sure I've got your point
not sure what you are trying to do but if you are trying to display all columns, you can use a foreach loop
while($row = mysql_fetch_array($query)){
foreach($row as $key=>$value)
{
echo("<b>$key</b>$value<br/>");
}
}
right guys im having trouble with one.
what i want to do is have a variable which is made from a mysql query. the problem i have is that it needs to contain multiple rows from the query and combine them into one.
currently i have
$lender = mysql_query("Select * from lender where reference = '$reference'");
while($lenderrow=mysql_fetch_array($lender)) {
$lender1 = $lenderrow["lender"] . " " . $lenderrow["lenderref"] . " " . "£" . $lenderrow["amount"]
echo '<br />';
}
so basically i want it to take this format if it has multiple rows
blackhorse htfhg125h £250
santander htdhfr58hryf £541
Test 125452asaed2 £760
currently i only get the last result when i echo $lender 1 (obviously because its the last call in the while loop)
Cheers In Advance
You need to use a other array.
<?php
$lender = mysql_query("Select * from lender where reference = '$reference'");
$formated_lender = array();
while ($lenderrow=mysql_fetch_array($lender)) {
$formated_lender = $lenderrow["lender"] . " " . $lenderrow["lenderref"] . " " . "£" .
$lenderrow["amount"];
}
foreach ($formated_lender as $row)
{
echo $row . '<br />';
}
Or, if you would just one variable containing all the row, replace $lende1 = ... by $lender1 .= ...
Just put your echo inside the loop. A loop isn't restricted to one statement.
$lender = mysql_query("Select * from lender where reference = '$reference'");
while($lenderrow = mysql_fetch_array($lender)) {
$result = $lenderrow["lender"] . " " . $lenderrow["lenderref"] . " " . "£" . $lenderrow["amount"];
echo $result . "<br />";
}
If you want it in an array, you can use an empty while loop too:
$lender = mysql_query("Select * from lender where reference = '$reference'");
$results = array();
while($results[] = mysql_fetch_array($lender)); // Empty loop
Also, you might want to be careful about SQL injection if $reference is user-supplied and unescaped.