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.
Related
i have this query :
SELECT *
FROM news
WHERE STATE LIKE 'SI'
AND data<'".time()."'
ORDER
BY data DESC
limit 0,1
and i would like to know if the function time it's correct because there is an error on synthase.
thank's you !
There are reserved words in MySQL which you cannot use as column names without clearly indicating they are names. See:
https://dev.mysql.com/doc/refman/5.7/en/keywords.html
Both 'data' and 'date' are reserved words. Use back ticks to indicate they are used as names:
$query = "SELECT *
FROM `news`
WHERE `STATE` LIKE 'SI'
AND `data` < '".time()."'
ORDER
BY `data` DESC
LIMIT 0,1
or better, in my opinion, use better column names:
$query = "SELECT *
FROM newsItems
WHERE itemState LIKE 'SI'
AND creationDate < '".time()."'
ORDER
BY creationDate DESC
LIMIT 0,1";
As you can see I had to guess what the columns really stand for, because it's not directly clear from the names. It should be, because that's what they are there for.
TIME() is a function in which you also need to pass your parameter.
So, instead of using it blank like:
select TIME();
you need to use it in this way:
select TIME(now());
Note: In your query, you need to pass like (only if you have datetime field in your table):
AND time(data) < time(now())
This is my query:
$query = "SELECT * FROM table ORDER BY 'timestamp' LIMIT $startAt, $perPage";
I'm trying to sort the results by the latest (latest on top), so I tried to add DESC.
But where ever I put it in the query it gives me an error, the only way it doesn't give an error is like this:
$query = "SELECT * FROM movies ORDER BY 'timestamp' DESC LIMIT $startAt, $perPage";
But even though it doesn't give an error, it still doesn't work.
This probably seems like a silly thing to ask but it's really driving me crazy
Timestamp is the datatype in MySQL. So, always try to avoid such column name in your table. Even, if you have a column named as timestamp, you must have to use backtick. So, use below query:
$query = "SELECT * FROM table ORDER BY `timestamp` LIMIT $startAt, $perPage";
Try backtick on timestamp :
$query = "SELECT * FROM movies ORDER BY `timestamp` DESC LIMIT $startAt, $perPage";
Using backticks permits you to use alternative characters
I think however, instead of mandating whether or not you can use backticks, they should have a standard for names. It solves more 'real' problems.
Do not use quote in field name. Try this:
$query = "SELECT * FROM movies ORDER BY timestamp DESC LIMIT $startAt, $perPage";
How to select results from table where cat = '$cat' and if it's not equal then select all from cat no matter what $cat is.
Here is my query
$sql = mysql_query("SELECT * FROM `obiavi` WHERE `postdate`+`days`*86400 > $time AND `town` IN ('$oblasti') AND `desc` LIKE '%$keyword%' ORDER BY id DESC LIMIT $start, $perpage") or die (mysql_error());
From my understanding, you want only results where cat = '$cat'. If you obtain no results, then you want to have results no matter what their cat is.
This cannot be done effectively in a single query, you need to use two queries.
If your first query with the condition returns no results, then you attempt the second query, without the cat condition.
Best practices
Consider defending yourself against MySQL Injections
Also, please consider using MySQLi or PDO instead of MySQL.
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 am using the below code to try and echo out the latest 5 entries on the MySQL table, I cannot, however seem able to figure how to limit the number of results, can anyone help me out by allowing me to limit the number of results to 5 rows?
<table>
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/resources/pdo.php");
$q = "SELECT * FROM `content` ORDER BY `id`";
$query = $pdo->query($q);
$data = array_reverse($query->fetchAll());
foreach ($data as $row) {
echo "<tr><td>{$row['title']}</td><td>{$row['id']}</td></tr>";
}
?>
</table>
Thanks!
Please note that I am new to PHP and I need help so if this question isn't useful, help me because I have only just started this.
Use LIMIT clause in your SQL query:
SELECT * FROM `content` ORDER BY `id` DESC LIMIT 5
From the manual:
The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).
With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):
Use the LIMIT word:
SELECT * FROM `content` ORDER BY `id` DESC LIMIT 5
order by id desc to get rid of the array_reverse and limit 5 to cap the number of returned results.
$q = "SELECT * FROM `content` ORDER BY `id` DESC LIMIT 5";
...
$data = $query->fetchAll();
As a global guideline: when writing queries try to formulate them in such a way that the resultset is as close to what you need as possible, ie no extra sorting or filtering operations afterwards.
having the dbserver send data that you aren't going to use is a waste
having to resort/refilter data on the webserver costs webserver performance and, in the case of big resultsets, it can cost lots of memory as well
When pulling data from a database you normally set a LIMIT via the MySQL-query, instead of counting the loop-iterations when reading the returned data.
$q = "SELECT * FROM `content` ORDER BY `id` LIMIT 5";