How to select posts from database that contain certain word? - php

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

Related

How to select the top third row in mysql

Guys am trying to select the top/recently third row, i tried this one but it doesn't work, where do i make mistake ?
<?php
$sql = "SELECT * FROM songs ORDER BY id ASC LIMIT 1,2;";
$result = mysqli_query($con, $sql);
$resultCheck = mysqli_num_rows($result);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['artist'];
}
}
?>
Use OFFSET:
SELECT * FROM songs ORDER BY id ASC LIMIT 1 OFFSET 2
The shorthand (which you are using) is reversed, so OFFSET is first then LIMIT:
SELECT * FROM songs ORDER BY id ASC LIMIT 2,1;
Use OFFSET
Here the limit 1 It simply means and you need one record
and the offset means skip the first 2
SELECT * FROM songs ORDER BY id ASC LIMIT 1 OFFSET 2
The parameters you use after limit should be reversed.
The first parameter is offset, and the second parameter is number of record you want.
SELECT * FROM songs ORDER BY id ASC LIMIT 2,1
This is just my opinion--
Sorting like this should always be done in client software.
Extract the data - remove the ORDER BY for your SQL...
Sort it in your client, and select and return the third line to the caller.
You will get better scalability and maintainability than driving all of this through an SQL query.
This is my go-to approach when solving these types of problems through custom software and it has been proven out over time.
Think about this:
Select ID from songs
get the id's into your code, and sort them there. Then chose the third one in the list. Then:
select title, author, artist, ... from songs where ID = VALUE FROM ID ABOVE
Yes, you are hitting the database twice, but these are two very efficient queries and that will perform better as your database scales, than the fancy order by you propose.

Retrieve table ID from selected row

So I've been stuck on this for a while and I can't find anything on google for this specific thing.
I have this small snippet of code
$link = mysqli_connect("localhost", 'username','password',"database");
$sql = "SELECT * FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
Which should select the latest table by order of id's right?
Well what I want to do is return this id. So if I have 5 items/rows I want to grab the latest (5 in this case) id of the table, and return it. With the eventual goal of using this returned id in javascript but that's a worry for later, right now I just want it in plaintext where the result should only be the id.
This is probably a duplicate question but I can't for the life of me find what I should google to get there
EDIT:
I guess I should clarify further. I know I'm able to do
$sql = "SELECT ID FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
but whenever I try to actually retrieve it/print it its returned as a string instead of the ID.
EDIT 2: I, thanks to some comments, have managed to figure it out. Sorry for the badly worded everything, I'm new to this and as I said don't know how to word it.
SOLUTION:
After just throwing away the $sql thing I added:
$result = mysqli_query($link,"SELECT * FROM `uploads`");
Then I simply did
echo mysqli_num_rows($result);
To echo out the number of rows/what I called the "ID".
Sorry for all the confusion, thanks to those that tried to help. To the others there's no need to be rude.
If I understood your question correctly, you want to get the ID field only, so you have two options:
Option 1 (Recommended)
Given your code
$sql = "SELECT * FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
Change it to:
$sql = "SELECT ID FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
This way, your getting just that ID field you're after. Nothing else is returned from each row.
Option 2
Keep your sql query as it is, and get the ID field from each row in your results (it's an array, so you can retrieve only one field by using its index or name).
Of course, I assume there's an ID field in your table!
Just select the ID.
SELECT id
FROM uploads
ORDER BY id DESC
LIMIT 1;
Simply select what you want.
$sql = "SELECT id FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
The * means you want to select every column there is. However, SQL gives you the possibility to select the specific columns you want. You could also do something like
$sql = "SELECT id, name, title, somethingelse FROM `uploads` ORDER BY id DESC LIMIT 0, 1";
and you'd receive these 4 fields as an array.

When bringing two tables together how can I make only Photos searchable?

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';
}

PHP and Mysql || 'or' syntax?

In mysql I have something like:
$currentname = mysql_query("SELECT * FROM posts LIMIT $start, 5 WHERE ");
How can i do something like this below that works:
$currentname = mysql_query("SELECT * FROM posts LIMIT $start, 5 WHERE `title` LIKE '%{Hello world}%' || Where `text` LIKE '%{Hello World}%'");
Something like above that will actually work.
Try this:
$queryResult = mysql_query("SELECT * FROM posts WHERE `title` LIKE '%{Hello world}%' OR `text` LIKE '%{Hello World}% LIMIT $start, 5'");
$currentName = mysql_fetch_assoc($queryResult);
if you expect many results...
while($currentName = mysql_fetch_assoc($queryResult)) {
//your code here...
}
Replace || with OR and remove the extra WHERE that comes after it. In SQL, || is OR and && is AND. You can read more here.
Note: Please take time to read manuals, it absolutely helps.
You can use OR in MySql, and it is likely very suitable for most situations.
OR however has a slight disadvantage performance wise as for each OR query the whole query is ran again. I am no MySql performance guru, but it would seem UNION is better optimized. So in general, and at lest with more OR statements you should use a UNION like this:
SELECT your_union_result.* FROM
(
SELECT * FROM posts WHERE `title` LIKE '%{Hello world}%'
UNION
SELECT * FROM posts WHERE `text` LIKE '%{Hello World}%'
) AS your_union_result
ORDER BY your_union_result.order_column
LIMIT $start, 5
Please note: My version has a subquery. You need it in case you want to order the result or limit the total rows. You now have a few options to fetch the actual result.
You can fetch_assoc(), fetch_array() and so on row by row. It is unclear for me what you want as the actual result. The $currentname indicates a post or user name, but a limit of $start, 5, indicates you want a list.
Go ahead and read http://php.net/manual/en/function.mysql-fetch-array.php and the other fetch functions. If you need more help, please update your question to be a bit more specific.

What is the correct MySQL syntax to retrieve data with multiple parameters

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

Categories