dthjnc306679 2013-10-10 13:09
浏览 21
已采纳

PHP内爆函数说明

I am relatively new to PHP. The textbook im working from covers PHP5.2 and mentions nothing of implode. The information im getting from PHP manual is a bit unclear to me. Im looking for a short clear explanation and example on implode

  • What exactly is its purpose?
  • Why would you use it?
  • Is it secure?

I know implode returns a string of the elements of its array but how is the following 2 exmples different, and why would you use one over the other:

example 1

$query = 'SELECT `name`, `position` 
        FROM `player_info` 
        WHERE `player_id` IN (' . implode(',', $player_ids) . ')';

example 2

 $result2 = mysql_query("SELECT `fixture_id`, `opponents` 
                         FROM `fixtures` ") or die (mysql_error());

Thank you

  • 写回答

5条回答 默认 最新

  • dpquu9206 2013-10-10 13:15
    关注

    Implode can be particularly useful for lists. Say you have an array of ingredients, you might echo implode(" ",$ingredients) to show them on their own lines.

    In your first example, you need to be very careful. It will only work properly if $player_ids is an array of numbers. implode() by itself is perfectly secure, however improper use can leave gaping holes in your security. A more "correct" version of that code might look like this:

    $query = "SELECT `name`, `position` FROM `player_info`
      WHERE `player_id` IN ('".implode("','",array_map("mysql_real_escape_string",$player_ids))."')";
    

    The above code also handles the case where $player_ids is empty. In your code, it will result in a MySQL syntax error (IN () is not valid), whereas in this code it will simply look for IN (''), which will match no rows.

    Another use for implode might be when packing numbers. Say you have an array of digits, you might implode("",$digits) to pack them into a single string (and str_split($string) to unpack them).

    In short, there are many potential uses for this function, and generally it will be obvious when the function applies. Try not to think too hard about it ;)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 如何实验stm32主通道和互补通道独立输出
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题