I've brought two tables together from one database which has a search function applied. At the moment 'photos' are being narrowed down when searching but the contents from 'sponsor' is always displayed. Ideally I want everything to be displayed before searching but then on a search 'sponsor' results will never appear. I've tried to put the $search in the first half with 'photos' but that does the above action. What can I add to stop this?
SELECT * FROM photos
WHERE title LIKE '%".$search."%'
UNION SELECT * FROM sponsor
ORDER BY id DESC
You could use two different SQL statements depending on whether or not $search is present.
if ($search) {
$sql = "SELECT * FROM photos
WHERE title LIKE '%".$search."%'
ORDER BY id DESC";
} else {
$sql = 'SELECT * FROM photos
UNION SELECT * FROM sponsor
ORDER BY id DESC';
}
Related
I have made a search form which is showing results successfully from 1 table "links", but I want the results to be searched from multiple tables like "links1" "links2".
This is my coding
$orderby = " ORDER BY id desc";
$sql = "SELECT * FROM links " . $queryCondition;
$result = mysqli_query($conn,$sql);
This is a perfect problem for that UNION SELECT can solve. Say you have two tables, links1 and links2, both with the exact same column names. What you can do in SQL then is SELECT * FROM links1 UNION SELECT * FROM links2 and that will return the data as if both tables were beneath each other. For more info read https://www.w3schools.com/sql/sql_union.asp
how would i go about ordering by a value that is not in the table where i am selecting from, in this instance the value $count1 is not in the table search.
count has the same identifying id as that of the thing it is being reffered to in the other table, this is where count1 is grabbed
$q = $db->prepare("SELECT COUNT(rating) FROM ratings WHERE id='$id' AND rating = 'd'");
$q->execute();
$count1 = $q->fetchColumn();
$query = "SELECT * FROM search WHERE title LIKE '$each' ORDER BY '$count1'"
$query = $db->prepare($query);
$query->execute();
that is from ratings, how would i go about ordering the entries like that, so that they are based off the number of count1 and are decided, i might have to implement something like
$query = "SELECT * FROM search WHERE title LIKE '$each' AND id = '$id' ORDER BY '$count1'"
$query = $db->prepare($query);
$query->execute();
Possible Duplicate: Mysql order by specific ID values
Same thing here, you'll just output your $count1as a comma separated string and add it in the SQL query as ORDER BY FIELD(COUNT,___comma_sep_string___)
ratings is a table, not a database. You can join tables or use subqueries to get the desired result, without having to make multiple queries.
You haven't described how the FOREIGN_KEY is set up in the ratings table, but assuming you have something ratings.search_id, this should work:
SELECT search.*, (SELECT COUNT(rating)
FROM ratings
WHERE ratings.search_id = search.id
AND rating = 'd'
) AS rating_count
FROM search
WHERE title LIKE '$each'
ORDER BY rating_count
I am retrieving data from a database with php and MySQL as follows
$query = mysql_query("SELECT * FROM pictures WHERE (title LIKE '%$Search%' OR keywords LIKE '%$Search%') AND approved = 'YES' ORDER BY title ASC");
The query is correct and there are no errors and the query works fine for "title LIKE '%$Search%'" but the parameter "OR keywords LIKE '%$Search%'" is not retrieving data. The parameter "AND" also works correctly.
The keywords are stored in the database for example "pizza, restaurants, take away" but I don't see that is a problem.
My question is "What is the correct syntax for applying the "OR" parameter?
Remove the brackets around (title LIKE '%$Search%' OR keywords LIKE '%$Search%')
Those are generally used for subqueries.
$query = mysql_query("
SELECT * FROM pictures
WHERE title LIKE '%$Search%'
OR keywords LIKE '%$Search%'
AND approved = 'YES'
ORDER BY title ASC
");
https://dev.mysql.com/doc/refman/5.0/en/subqueries.html
Here is an example of a subquery, and pulled from the manual on MySQL.com:
SELECT * FROM t1 WHERE column1 = (SELECT column1 FROM t2);
Edit:
Or try a different quoting method:
$query = mysql_query("
SELECT * FROM pictures
WHERE title LIKE '".%$Search%."'
OR keywords LIKE '".%$Search%."'
AND approved = 'YES'
ORDER BY title ASC
");
You could also try escaping your data:
$Search = mysql_real_escape_string($Search);
as an example. I don't know how you're assigning that variable.
phpMyAdmin test edit:
This is what I used inside phpMyAdmin:
SELECT * FROM table
WHERE col1 LIKE '%pizza%'
OR col2 LIKE '%pizza%'
AND col3 = 'YES'
ORDER BY col1 ASC
using pizza as the search keyword seeing that $Search will be based on the same keyword for you, where columns contain "large pizza" in one, and "pizza, take away, restaurants" in another.
Remember that, whatever you're using/assigning $Search to, must reside inside all your queried columns.
You may also want to make use of explode().
Here is an example pulled from https://stackoverflow.com/a/15289777/
<?php
$search = 'Gold Chain Shirt';
$bits = explode(' ', $search);
$sql = "SELECT name FROM product WHERE name LIKE '%" . implode("%' OR name LIKE '%", $bits) . "%'";
The above will generate this query:
SELECT name FROM product WHERE name LIKE '%Gold%' OR name LIKE '%Chain%' OR name LIKE '%Shirt%'
Sorry for taking some time but this is my working answer to my own question... not the prettiest syntax but it works without any string functions or explode functions. MySql can handle keywords quite well without any other functions being included:
$query = mysql_query("SELECT * FROM pictures
WHERE
title LIKE '%$Search%' AND featured IS NOT NULL AND streetview IS NOT NULL AND (id_user > '1') AND (status = '1')
OR
keywords LIKE '%$Search%' AND featured IS NOT NULL AND streetview IS NOT NULL AND (id_user > '1') AND (status = '1') ORDER BY title ASC");
Thank you all for your contributions
I'm working on search on my website and I would like to select posts from database that contain word (or words) that user searched.
I'm using code below and it works, but since I'm using LIMIT 10, it can happen that in 10 selected posts, for example, only 2 posts contain searched word, so only 2 posts will be displayed, even if there are more posts in database that contain searched words.
$posts = mysql_query("SELECT * FROM posts ORDER BY id DESC LIMIT 10");
while($posts_row = mysql_fetch_assoc($posts )) {
...
$post_body = $posts_row ['post_body'];
if (strstr($post_body, $search)) {
echo $post_body;
}
...
}
Is there a way to only select posts from database that contain searched word?
Something like
$posts = mysql_query("SELECT * FROM posts WHERE strstr($post_body, $search) ORDER BY id DESC LIMIT 10");
EDIT: Thank you for your help and advices.
Try this (tested in MySQL , am not sure for others):
"SELECT * FROM posts WHERE post_body LIKE ( '%".$search."%' ) ORDER BY id DESC LIMIT 10"
First: Don't use mysql_ - it's deprecated and is being phased out for security reasons. Use mysqli_ instead.
Second: Use 'like' to do so:
SELECT * FROM tableName WHERE columnName LIKE '%keyword%';
Will find matches in data values of 'keyword searches are fun' also 'Find this keyword' and 'all keywords are words.'
You can utilize LIKE to do this search.
SELECT * FROM posts WHERE post_body LIKE ('%?%') ORDER BY id DESC LIMIT 10;
Here post_body would be whatever filed stores the post content and ? would be replaced by your search string.
You can use this as a query:
SELECT * FROM posts WHERE $post_body like '%$search%' ORDER BY id DESC LIMIT 10
This is probably very limiting and slow though. Depending on how big your application and how much data you have, you might want to give "Full-Text Search".
Full-Text Search
I'm working on the photo section of my website, but more precisely on the next/previous link with sorting options.
There are two different option for sorting that exist, first there is a filter (Latest, Trending, Favorite, User etc.) and secondly a sorting option for some of the previous filters (date, views, ratings etc.)
I am having trouble finding a good solution for easily retrieving the next/previous picture for my slideshow.
This is the little bit of SQL I have for getting the next picture for a filter:latest
if ($filter == "latest") {
$sql = "SELECT *
FROM photos
WHERE status = 0 AND id < ".$id."
ORDER BY id DESC
LIMIT 1
";
$result = $db->sql_query($sql);
$sql2 ="SELECT *
FROM photos
WHERE id = (SELECT MAX(id) FROM photos WHERE status = '0')
ORDER BY id DESC
LIMIT 1
";
}
I am wondering if there is an easier way to implement this in my project ? maybe a php class exists to do something like this ?
I feel like I'm going to spend a long time getting all these SQL queries to work properly if I have to do it all like this.
Edit
This is the layout of my photos table
`id` -> unique ID, autoincremented
`title`
`img_name` -> contains the image file name
`date_created` -> when the picture was uploaded
`uploader` -> id of the user that uploaded
`views` -> number of views the picture has
`up_votes` -> votes used to calculate the Wilson score interval
`down_votes`
`net_votes` -> up vote minus down votes
There are other tables like one that links user with friends they have, it is called users_friends
`user_id` -> contains id of the user that added the friend
`friend_user_id` -> contains id of the friend in question
With these two tables I am able to get all the pictures posted by the friend of a user using this sql query :
SELECT *
FROM photos
WHERE uploader IN
(
SELECT friend_user_id
FROM users_friends
WHERE user_id = ':user_id'
)
ORDER BY id DESC
I then have two queries to get the link to the next picture and 2 other queries for the previous one. I have two because one is for when you get at the end of the database to go back to the other end and the other one is for all the other queries. And they look something like this (I'm only posting the next button here)
$sql = "SELECT *
FROM photos
WHERE status = 0 AND id < ".$id." AND Uploader IN (SELECT friend_user_id FROM users_friends WHERE user_id = ".$logedInUser['User_ID'].")
ORDER BY id DESC
LIMIT 1
";
$sql2 ="SELECT *
FROM photos
WHERE id = (SELECT MAX(id) FROM photos WHERE status = '0' AND Uploader IN (SELECT friend_user_id FROM users_friends WHERE user_id = ".$logedInUser['User_ID']."))
ORDER BY id DESC
LIMIT 1
";
$result = $db->sql_query($sql);
if (mysql_num_rows($result)==1) {
$row = $db->sql_fetchrow($result);
return "/photo/".$row["id"]."/".urlFriendly($row["Title"])."/".$filter.$sort;
}
else
{
$result = $db->sql_query($sql2);
$row = $db->sql_fetchrow($result);
return "/photo/".$row["id"]."/".urlFriendly($row["Title"])."/".$filter.sort;
}
I feel like there is a lot of stuff that could be simplified, but I don't yet know how to do it.
I also have the Lower bound of Wilson score sql code to implement for the next/previous button, and it is quite a bit sql code to have to write 4 time. Maybe that I can insert the Wilson score in the photos table, which could simplify a lot the sql code.
It would be helpful if you could post the structure of your table - i.e. what columns/types you have and what each row represents. I'll assume that you have a table where each row represents a photo, and that each photo has an ID, filename, and various other columns that help you filter/sort (such as date, favorite, etc.).
If your filtering and sorting preferences are defined by the user, you can then use those in a single SQL query, whereby you get the full set of ordered results. For instance:
$sort = date;
$filter = favorite;
$sql = "SELECT ID, filename, [other vars here]
FROM photos
WHERE " . $filter . " = TRUE
ORDER BY ". $sort . " DESC";
$result = $db->sql_query($sql);
Now, you can use a function such as mysql_fetch_array to step through each row in your result set and populate some kind of data structure with the current, previous, and next photos.