Good evening. I'm currently working on a school project and I got stuck. This is the code:
foreach ($Pessoas as $key => $value) {
$ids = $ids . " OR id_Pessoas = " . $Pessoas[$key]['id'];
}
if (substr($ids, 0, 3) == " OR ") {
if (substr($ids, 0, strlen(" OR ")) == " OR ") {
$ids = substr($ids, strlen(" OR "));
}
}
That's part of a controller for my search system in PHP, which I'm trying to pass on to the model. I'm working, as you might have figured, with MVC using Slim Framework and PDO. The idea was to search a keyword and search for profile's names or tags with that keyword. I would first search profile names with this query: SELECT * FROM Pessoas WHERE nome LIKE :keyword AND hidden = 0
and everything was good until I tried to use that code above to take the id's so I could generate a piece of code to complete the following query SELECT * FROM Pessoas_tags WHERE
, but it's not working.
The idea behind the code above was to generate something like " OR id_Pessoas = 1 OR id_Pessoas = 4"
and then remove the first " OR "
so it didn't give an error but it's not removing. I don't really know why and that piece of code isn't really mine, but I don't know where I took it from, since it was a few months ago.
I hope it's just a silly error. If instead of doing this you have a better solution I'd also appreciate you sharing it here. Thanks for your patience and help in advance.
There's something wrong with your code. This should remove the " OR ":
foreach ($Pessoas as $key => $value) {
$ids = $ids . " OR id_Pessoas = " . $Pessoas[$key]['id'];
}
if (!empty($ids) && substr($ids, 0, strlen(" OR ")) == " OR ") {
$ids = substr($ids, strlen(" OR "));
}
Alternatively, since the condition is OR, you can add an invalid statement that will always be false and you don't have to remove any " OR " to make it work. Somewhat like this:
$ids = "1 != 1";
foreach ($Pessoas as $key => $value) {
$ids = $ids . " OR id_Pessoas = " . $Pessoas[$key]['id'];
}