2

So I have this string in my MySQL Database:
The string is on a single row: 25 12 6 3 780

-I want to check if for example a variable $data='6', is in the string above;
Return the value of the data if TRUE, and FALSE otherwise;

SELECT * FROM table_name WHERE column_name LIKE '%$data%'

doesn't work because it returns all the string...
Any ideas?

2
  • It returns all the string, isn't that what you want? or all strings? Commented Feb 18, 2016 at 13:13
  • @sagi I want to check if the value of $data is in the string, and return it if true; Commented Feb 18, 2016 at 13:45

2 Answers 2

2

This will returns how many times the exact data exists in particular stings:

Solution 1:

$query = "
    SELECT COUNT(*) AS dataCount 
    FROM table_name t 
    WHERE FIND_IN_SET('".$data."',REPLACE(t.column_name,' ',',')) > 0";

php version(1):

$result=mysql_query("SELECT COUNT(*) AS dataCount FROM table_name t WHERE FIND_IN_SET('".$data."',REPLACE(t.column_name,' ',',')) > 0");
$data=mysql_fetch_assoc($result);
$value=$data['dataCount'];

This will returns all the strings where the exact data exists in:

Solution 2:

$query = "
    SELECT * 
    FROM table_name t 
    WHERE FIND_IN_SET('".$data."',REPLACE(t.column_name,' ',',')) > 0";

php version(2):

  $result=mysql_query("SELECT * FROM table_name t WHERE FIND_IN_SET('".$data."',REPLACE(t.column_name,' ',',')) > 0");
  $data=mysql_fetch_row($result);
Sign up to request clarification or add additional context in comments.

2 Comments

@mitiksoft , the first solution works just fine for my problem, it returns what is should, now I will see how to return the value in php to assign it to a variable, thanks for the help!
It will be great if you are stop using mysql_* functions, use mysqli_* instead.
0

You can use if (exists (...))

 select if (exists (SELECT * 
           FROM table_name 
           WHERE column_name LIKE '%$data%'), 1,0) ;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.