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

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大