douliu1092 2018-07-07 22:12
浏览 49
已采纳

PHP - 替换我的一段字符串

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.

  • 写回答

1条回答 默认 最新

  • donglu7286 2018-07-07 22:21
    关注

    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'];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?