-1

Table

enter image description here

Hello i try to finds all hashtags with name #c3 and mysqli query show me: 3 rows but correct is 2 rows with #c3 ??? where is problem ? I want to show me 2Rows !

$sql_query = mysqli_query($Connection, "SELECT * FROM my_table WHERE hashtag LIKE '%#c3%'");
echo mysqli_num_rows($sql_query);
Dharman
  • 30,962
  • 25
  • 85
  • 135

5 Answers5

2

To answer this and as left in comments (by myself)

Use '%#c3' by removing the last %

Using LIKE, the % wildcard does the following and a few examples:

%XXX% - Matches anything before and after XXX

%XXX - Matches anything before XXX

XXX% - Matches anything after XXX.

References:

Plus, should there be any user input, consider using a prepared statement:

It will help against a potential SQL injection.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
0

Hi Your query is wrong try to use this

SELECT * from my_table WHERE FIND_IN_SET('#c3', hashtag);

FIND_IN_SET returns the position of a string if it is present (as a substring) within a list of strings. The string list itself is a string contains substrings separated by ‘,’ (comma) character.

for more info read http://www.w3resource.com/mysql/string-functions/mysql-find_in_set-function.php

Passionate Coder
  • 7,154
  • 2
  • 19
  • 44
0

You can use FIND_IN_SET

SELECT * FROM my_table WHERE FIND_IN_SET('#c3',hashtag)

See docs here and example here

Tamil
  • 1,193
  • 9
  • 24
0

Split the table into 2 tables:

post: id | text | date
       1
       2
       3

post_hashtag: post_id | hashtag
                1         #c1
                1         #c3
                2         #c3
                3         #c3blabla

Then your query becomes:

SELECT post.*,post_hashtag.hashtag FROM post JOIN post_hashtag ON post.id=post_hashtag.post_id WHERE hashtag='#c3#';

The act of splitting the table is called normalizing and you need to do this because your tables are not in any normal form which makes them not relational which defeats the purpose of storing them in a relational database. Check https://en.wikipedia.org/wiki/First_normal_form for more information.

apokryfos
  • 38,771
  • 9
  • 70
  • 114
0

Looking at your table, I would suggest that you break up your tables to have a many to many link for hashtag. That way you can search for all records that have a matching hashtag.

data table
+----+------+------+
| id | text | date |
+----+------+------+

hash table
+----+------+
| id | hash |
+----+------+

link table
+---------+---------+
| data_id | hash_id |
+---------+---------+

This would then allow you to use an SQL statement like:

SELECT * FROM data
INNER JOIN link ON data_id = data.id
INNER JOIN hash ON hash_id = hash.id
WHERE hash = '#3';
Carl Casbolt
  • 102
  • 6