-2

I will try to better explain what I am looking for.

I want to check all rows from mysql database that has one of item in its column.

Lets say that I have database with 3 columns :id,name,tags

This is how my database looks

and variable $interests = "nature,sky,tehnology"

I want to search all rows of my database and return true if there is at least one match of word of $interests inside column tags

Example:

If variable is: $interests = "nature,sky,tehnology,math;"
and column tags has value of nature,sky,tehnology How can I use SQL to check if there are things that are in both variable $interests and in column tags

So result from example would be true because there are 3 things that are in both variable and column: nature,sky,tehnology

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

-1


You can check if there's a match like this: (OOP)

$sql = $dbconnection->query('SELECT * FROM table_name WHERE interests = $interests');
if($sql->num_rows > 0) {
// do whatever you want to do when there is a match
} else {
echo 'No match has been found!';
exit();
}

Procedural style:

$sql = mysqli_query($dbconnection, 'SELECT * FROM table_name WHERE interests  = '.$interests);
if(mysqli_num_rows($sql) > 0) {
// do whatever you want to do when there is a match
} else {
echo 'No match has been found!';
}

I don't know if you're familiar with prepared statements, but I do recommend you using them.
OOP & Prepared statements:

$sql = $dbconnection->prepare('SELECT * FROM table_name WHERE interests = ?');
$sql->bind_param('s', $interests);
$sql->execute();
$sql->store_result();
if($sql->num_rows > 0) {
// do whatever you want to do when there is a match
} else {
echo 'No match has been found!';
exit();
}

I also recommend you using MySqli instead of MySql, since MySql is deprecated for PHP7 and MySqli does support Prepared Statements and MySql does not. (When should I use MySQLi instead of MySQL?)
I hope this helped you.

Edit
You need to fetch all rows.

$sql = $dbconnection->query('SELECT * FROM table_name);
$result = $sql->get_result();
$row = $result->fetch(MYSQLI_ASSOC);
$result->free_result();

And then you search in the $row variable for a match.
I recommend you using an array for $interests, because it's easier to search in the indexes. (You can use array_search / in_array)

JVT038
  • 18
  • 1
  • 10
  • Can you please look at question again? I eddited it. Problem is that I need to check if at lease 1 word from tag interests matches the value from tags – Rifet Gazdic Sep 14 '19 at 16:50