【问题标题】:PHP - how to get array value by key received from GETPHP - 如何通过从 GET 接收的键获取数组值
【发布时间】:2012-11-13 10:25:34
【问题描述】:

如何循环遍历所有短语并将它们作为链接列表输出,并带有 GET 参数?

如何创建一个数组,用整数索引,然后使用 GET 变量选择其中一个短语。

到目前为止我的代码;

$arr = array('1' => 'Que será, será.', '2' => 'C’est la vie!', '3' => 'Sich nicht um ungelegte Eier kümmern.', '4' => 'Ada asap, ada api.', '5' => 'Batti il ferro finché è caldo.');
?> 

<p><?php print $arr[1]; ?> - Whatever will be, will be.</p>
<p><?php print $arr[2]; ?> – That’s the life.</p> 
<p><?php print $arr[3]; ?> - Don’t count your chickens before they hatch.</p> 
<p><?php print $arr[4]; ?> - There's no smoke without fire.</p> 
<p><?php print $arr[5]; ?> - Strike while the iron is hot.</p>

【问题讨论】:

  • 与您打印它们的方式相同:$arr[...],但 ... 将来自 $_GET。不是直接 $_GET['var'],因为这太信任用户输入了。
  • 编码有问题吗?为什么添加“字符”标签?

标签: php arrays string character


【解决方案1】:

应该这样做:

$key = (int)$_GET['key'];
if (isset($arr[$key]) {
   echo print $arr[$key]; 
} else {
   echo "Invalid option specified";
}

【讨论】:

  • 没有人提及 MySQL。
【解决方案2】:
<?php  
  $key = mysql_real_escape_string($_GET['value']);//Pass this value from url and sanitize the inputs
  ?>
  <p><?php print $arr[$key]; ?>

【讨论】:

    【解决方案3】:
    $key = $_GET['index'];
    $val = isset($arr[$key]) ? $arr[$key] : false;
    

    编辑:为什么人们一直推荐 mysql_real_escape_string?这是用于数据库查询转义并向数据库发送请求(据我所知)。密钥甚至不需要转义,因为它没有被发送到数据库或输出。

    【讨论】:

    • 有人指出这一点,对我来说只是习惯,我编辑了我的答案,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    • 2011-05-13
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 2016-10-24
    相关资源
    最近更新 更多