php select from mysql where title begins with A (and A alone) - php

I'm sure this is super easy, but can't seem to figure it out.. I need to select all titles from my database where the title starts with A, or B, or C etc. Here's what I've tried so far:
SELECT * FROM weblinks WHERE catid = 4 AND title LIKE 'A'
but returns nothing.. Could someone help me out with this?
Cheers

For titles starting in 'A' use a % after the A
SELECT * FROM weblinks WHERE catid = 4 AND title LIKE 'A%'
For titles with the letter 'A' in it, use % on either side of A
SELECT * FROM weblinks WHERE catid = 4 AND title LIKE '%A%'
For titles ending in the letter 'A', use % before the A
SELECT * FROM weblinks WHERE catid = 4 AND title LIKE '%A'
Basically % is a wildcard. It tells MySQL that anything can be in the location.
For having numbers as the first letter, check out Mark's answer.

The wildcards for LIKE are % and _, where % matches 0 or more characters and _ matches exactly one character.

The existing answers are correct for beginning with A:
SELECT * FROM weblinks WHERE catid = 4 AND title LIKE 'A%'
For beginning with any number you can use the REGEXP operator:
SELECT * FROM weblinks WHERE catid = 4 AND title REGEXP '^[0-9]'

try:
SELECT * FROM weblinks WHERE catid = 4 AND ((title like 'A%') OR (title like 'B%'))
so on and so forth

SELECT * FROM weblinks WHERE catid = 4 AND title LIKE 'A%'
% tells "anything", so it's "A" then anything. Only works with the LIKE comparison operator.

Related

select where row contains string

I have a column named software_hardware from the table activities which could have multiple product inputs separated by a pipeline like INVENTORY| POS | or GPOS | ACCOUNTING |.
I have this query:
SELECT a.id, a.ticket_number, a.client, a.software_hardware,
a.issues_concern, a.status, a.technical_programmer, a.date_added
FROM activities a
WHERE a.client = '".$_POST['client']."' AND a.software_hardware LIKE '%".$arr[$i]."%'
ORDER BY date_added DESC
$arr = explode("|", $_POST['Soft_hard']);
When I select a client and a product, related info would be displayed on a div. Now my problem is, if I have POS and GPOS, I realized I couldn't use LIKE '%[input product name here]%'as this would return results that contains both POS and GPOS if I selected POS.
How can I fix this query to not display GPOS if I selected POS?
PS. I am aware of the issues with MySQL. It's what the company I'm in uses so I have no choice at the moment.
You can use REGEXP:
a.software_hardware REGEXP '[[:<:]]" . $arr[$i] . "[[:>:]]'
the [[:<:]] and [[:>:]] markers stand for word boundaries. So POS cannot match GPOS as there would be no word boundary at the beginning.
Note you will need to trim($arr[$i]) if it has leading or trailing whitespace.
Try this:
SELECT a.id, a.ticket_number, a.client, a.software_hardware,
a.issues_concern, a.status, a.technical_programmer, a.date_added
FROM activities a
WHERE a.client = '".$_POST['client']."'
AND UPPER(a.software_hardware) LIKE '%".strtoupper($arr[$i])."%'
ORDER BY a.date_added DESC

SQL select from multiple tagsid in same row

If I want to select all recipeids that include one tagsid, for example:
tagsid = 1
recipeid = 2|12|1|8
If I use this code:
$query = "SELECT * FROM recipe where tagsid like '%".$tag_id."%'";
it will show recipeid 1 in tagsid 12, 1, but it should be only in tagsid 1. Why is this incorrect?
With delimiters, with delimiter after, but nothing before, or with delimiter before, but nothing after
$query = "SELECT * FROM recipe WHERE tagsid LIKE '%|".$tag_id."|%' OR tagsid LIKE '".$tag_id."|%' OR tagsid LIKE '%|".$tag_id."'";
Use FIND_IN_SET() on the tagsid column after replacing the pipes with commas.
$query = "SELECT *
FROM recipe
WHERE COALESCE(FIND_IN_SET($tag_id, REPLACE(tagsid, '|', ',')), 0) > 0"
By the way, you should avoid storing CSV in a column because it is difficult to work with.
You should find for an occurrence of the tag_id either between | or if the value starts from this tag_id with one | after. I think you always have | after tag_id.
$query =
"SELECT *
FROM recipe
where tagsid like '%|".$tag_id."|%'" or
tagsid like '".$tag_id."|%'";
Two cases should be considered:
%|<tag_id>|% - not on the first place
<tag_id>|% - on the first place
it will show recipeid 1 in tagsid 12, 1, but it should be only in tagsid 1. Why is this incorrect?
Because % symbol works as a wildcard meaning any number of any symbols.You search for %1% pattern. All strings with at least one 1 substring match the pattern. 12| as well.

MySQL sort by number of occurrences

I am doing a search in two text fields called Subject and Text for a specific keyword. To do this I use the LIKE statement. I have encountered a problem when trying to sort the results by the number of occurrences.
my search query looks like this:
SELECT * FROM Table WHERE (Text LIKE '%Keyword%' OR Subject LIKE '%Keyword%')
I tried to add a count() statement and sort it by the number of occurrences, but the count() statement just keep returning the number of rows in my table.
Here is the query with count statement:
SELECT *, COUNT(Text LIKE '%Keyword%') AS cnt FROM News WHERE (Text LIKE '%Keyword%' OR Subject LIKE '%Keyword%') ORDER BY cnt
What im looking for is something that returns the number of matches on the Subject and Text columns on each row, and then order the result after the highest amount of occurrences of the keyword on each row.
Below query can give you the no.of occurrences of string appears in both columns i.e text and subject and will sort results by the criteria but this will not be a good solution performance wise its better to sort the results in your application code level
SELECT *,
(LENGTH(`Text`) - LENGTH(REPLACE(`Text`, 'Keyword', ''))) / LENGTH('Keyword')
+
(LENGTH(`Subject`) - LENGTH(REPLACE(`Subject`, 'Keyword', ''))) / LENGTH('Keyword') `occurences`
FROM
`Table`
WHERE (Text LIKE '%Keyword%' OR Subject LIKE '%Keyword%')
ORDER BY `occurences` DESC
Fiddle Demo
Suggested by #lserni a more cleaner way of calculation of occurrences
SELECT *,
(LENGTH(`Text`) - LENGTH(REPLACE(`Text`, 'test', ''))) / LENGTH('test') `appears_in_text`,
(LENGTH(`Subject`) - LENGTH(REPLACE(`Subject`, 'test', ''))) / LENGTH('test') `appears_in_subject`,
(LENGTH(CONCAT(`Text`,' ',`Subject`)) - LENGTH(REPLACE(CONCAT(`Text`,' ',`Subject`), 'test', ''))) / LENGTH('test') `occurences`
FROM
`Table1`
WHERE (TEXT LIKE '%test%' OR SUBJECT LIKE '%test%')
ORDER BY `occurences` DESC
Fiddle Demo 2
You want SUM instead. Count will count how many records have non-null values, which means ALL matches and NON-matches will be counted.
SELECT *, SUM(Text LIKE '%Keyword') AS total_matches
...
ORDER BY total_matches
SUM() will count up how many boolean true results the LIKE produces, which will be typecast to integers, so you get a result like 1+1+1+0+1 = 4, instead of the 5 non-nulls count.
// escape $keyword for mysql
$keyword = strtolower('Keyword');
// now build the query
$query = <<<SQL
SELECT *,
((LENGTH(`Subject`) - LENGTH(REPLACE(LOWER(`Subject`), '{$keyword}', ''))) / LENGTH('{$keyword}')) AS `CountInSubject`,
((LENGTH(`Text`) - LENGTH(REPLACE(LOWER(`Text`), '{$keyword}', ''))) / LENGTH('{$keyword}')) AS `CountInText`
FROM `News`
WHERE (`Text` LIKE '%{$keyword}%' OR `Subject` LIKE '%{$keyword}%')
ORDER BY (`CountInSubject` + `CountInText`) DESC;
SQL;
Returns number of occurrences in each field and sorts by that.
The 'keyword' needs to be lower cased for this to work. I don't think it's really fast, performance wise as it needs to lower-case fields and there's no case-insensitive search in MySQL afaik.
You could index each news item (subject and text) by words and store in another table with news_id and occurrence count and then match against that.

Checking for string match with a MySQL query

I am trying to all grab rows of data from a data table, where one word matches a word within the text in my column 'story'.
Table Structure:
post_id | user_id | story
----------------------------------
1 | 1 | Hello World What's up?
2 | 4 | Hello guys!
3 | 7 | Working on shareit.me!
For Example:
I want to grab all of the posts containing the word hello (I am looking for case-insensitive).
How can I do this?
Here is what I have done so far:
// this will be the keyword! so use the variable $filter_tag in the query!
$filter_tag= $_GET['tag'];
//query for getting the users' posts containing the select tag
$query_posts= "SELECT * FROM posts WHERE user_id= '$user_id' ORDER BY post_id
DESC";
$result_posts= mysqli_query($connect, $query_posts);
Thanks!
$query_posts= "SELECT * FROM posts WHERE user_id= '$user_id' AND story LIKE '%$filter_tag%' ORDER BY post_id
DESC";
SELECT * FROM posts WHERE ... AND LOWER(story) LIKE '%hello%'
OR
SELECT * FROM posts WHERE ...
AND story COLLATE latin1_general_ci_ai LIKE '%hello%'
It would be:
SELECT * FROM posts WHERE ... AND story LIKE '%hello%'.
Generally the "%" is a wildcard (like '*'). So you can use 'hello%' '%hello%' and so on.
You can use the LIKE operator:
$query_posts = "SELECT * FROM posts WHERE user_id = $user_id AND story LIKE '%yourword%' ORDER BY post_id";
The % characters are like wildcards. % means match any number of characters, where _ (underscore) matches just one.
Note: I've removed the single quotes from your user_id column check too - this, being an integer, doesn't want to be in quotes - they are for strings.
Goes without say don't forget to escape the input.
$query_posts= "SELECT * FROM posts WHERE user_id = '$user_id' AND story LIKE '%".mysql_real_escape_string($filter_tag)."%'";
My answer is like the same, i made a sqlfiddle:
#supose the tag is Hello
SELECT * FROM posts
where story like "%Hello%";
PS: http://sqlfiddle.com/#!2/6bfcc1/5
The best solution will be to use MATCH() AGAINST() with an FULLTEXT index.

MySql query challenge - return results with whitespace?

I have a MySql database with some rows as follows:
ID DESC
1 This is my bike
2 Motorbikes are great
3 All bikers should wear helmets
4 A bike is great for exercise
5 A. Top. Bike.
What I want to do is return the rows with whitespace surrounding the search term, OR the term being at the end or beginning of the description.
For example,
"SELECT * FROM `mytable` WHERE `desc` LIKE '%bike%'"
Will return all rows. But,
"SELECT * FROM `mytable` WHERE `desc` LIKE '% bike %'
Will only return row 4.
What I really want is a reliable way to return rows 1, 4 and 5, i.e. where the search term is sorrounded with anything BUT chars A-z, 0-9. Any ideas? Is this even possible with MySql?
Thanks!!
You can use regular expressions in SQL
SELECT * FROM `table` WHERE desc REGEXP '\bbike\b'
You should start reading about MySql RegEx.
Sample Code.
SELECT * FROM table WHERE field_name REGEXP PATTERN;
More Specific
details Table
ID NAME
1 Dipesh
2 Dip
3 Dipe
4 DiDi
5 Di
SELECT * FROM details WHERE NAME REGEXP '^Di$';
Result
NAME -> Di
SELECT * FROM details WHERE NAME REGEXP 'Di$';
Result
NAME -> DiDi , Di
SELECT * FROM details WHERE NAME REGEXP '^Di';
Result
NAME -> Dip, DiDi, Di
You need to specify the additional conditions in the query:
SELECT *
FROM `mytable`
WHERE
`desc` LIKE '% bike %' OR
`desc` LIKE '% bike' OR
`desc` LIKE 'bike %';
Try this one, hope it'll help you
"SELECT * FROM `mytable` WHERE `desc` LIKE '% bike'

Categories