John Davidson

mysql - SQL Like Operator not working as expected in PHP

0 comments
Message:


I am trying to fetch all the data from the database with a certain content tags value. If I run the code below, it only returns the row with id 1, even though the word tag is part of the tags value in both rows. I also added %or% operator but it is fetching the exact row. When I search for tag it is showing 2 rows, but using the value in $mytags below, it match es only 1 row.


I want the expression to get a row if anything in $mytags matches.


SQL


$mytags = "tag, tag1";
SELECT * FROM table WHERE tags LIKE '%$mytags%' ORDER BY id DESC






















id body tags
1 Loreum Content 1 tag, tag1
2 Loreum Content 2 tag


My Answer:
In your SQL query, the LIKE operator is looking for an exact match of the string '%tag, tag1%' in the 'tags' column. This means that it will only return rows where the 'tags' column contains the exact string '%tag, tag1%'.

To achieve the desired result of fetching all rows where any part of the $mytags variable matches the 'tags' column, you can use the OR operator in your SQL query. Here's an example:

php
$mytags = "tag, tag1";
$tagsArray = explode(", ", $mytags);
$conditions = [];
foreach ($tagsArray as $tag) {
$conditions[] = "tags LIKE '%$tag%'";
}
$conditionString = implode(" OR ", $conditions);

$sql = "SELECT * FROM table WHERE $conditionString ORDER BY id DESC";


In this code snippet, we first split the $mytags variable into an array of individual tags using the explode() function. Then, we iterate over each tag in the array and construct a condition string that checks if the 'tags' column contains each tag using the LIKE operator. Finally, we concatenate all the individual conditions with the OR operator to form the final SQL query.

This way, the SQL query will return all rows where any part of the 'tags' column matches any of the tags in the $mytags variable.

Rate this post

4 of 5 based on 4428 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us