【问题标题】:php sanitize output form arrayphp清理输出表单数组
【发布时间】:2016-04-06 21:57:20
【问题描述】:

我有一个从 mysql 查询中获取数据的数组。

$mysql = "select distinct name from software";
$result = mysqli_query($conn, $mysql);
    while($myrow = mysqli_fetch_assoc($result)) {
      $array[] = $myrow;
}

我想做的是让数据输出如下:

item1, item2, item3

最后我想做的是能够将该信息存储在一个变量中以用于 mysql 查询

$array = item1, item2, item3

select * from table where item != ($array)

但是我无法正确输出数据,

如果我使用print_r,则显示数据并且数组很好。

如果我使用array_key(),我只能得到数字,我怎样才能得到名字?

print_r 输出:

( [0] => Array ( [name] => Skype for Business Basic 2016 - en-us ) [1] => Array ( [name] => Microsoft Visual C++ 2008 Redistributable - x64 9. ) [2] => Array ( [name] => Microsoft Office 365 Business - en-us ) [3] => Array ( [name] => Microsoft Silverlight ) [4] => Array ( [name] => NVIDIA 3D Vision Driver 341.92 ) [5] => Array ( [name] => NVIDIA Graphics Driver 341.92 ) [6] => Array ( [name] => NVIDIA Update 10.4.0 ) [7] => Array ( [name] => NVIDIA HD Audio Driver 1.3.30.1 ) [8] => Array ( [name] => FortiClient ) ) 

【问题讨论】:

  • implode(', ', $array)?
  • 也可以在谷歌上搜索sql not in
  • 你不能把这两个查询合并成一个查询吗?
  • 数组,数组,数组,数组,数组,数组,数组,数组,数组是我从 implode(', ', $array) 得到的全部内容

标签: php mysql


【解决方案1】:

当你这样做时:

while($myrow = mysqli_fetch_assoc($result)) {
    $array[] = $myrow;
}

对于您获取的每一行,您将整个行数组附加到$array。你可以改成

while($myrow = mysqli_fetch_assoc($result)) {
    $array[] = $myrow['name'];
}

只附加名称字符串。然后你会得到一个字符串数组而不是数组数组,implode 会给你你期望的结果。

【讨论】:

    【解决方案2】:

    您可以使用 array_column (PHP 5.5+) 来获取您想要的值:

    print_r(array_column($array, 'name'));
    

    【讨论】:

      【解决方案3】:

      您是否只使用第二个查询的输出而不使用其他内容?如果是这样,那么为什么将其存储在数组中?相反,你可以做类似的事情

      $namelist = "";
      $mysql = "select distinct name from software";
      $result = mysqli_query($conn, $mysql);
      while($myrow = mysqli_fetch_assoc($result)) {
        $namelist .= mysqli_real_escape_string($conn, $myrow['name']).",";
      }
      $namelist = substr($namelist, 0, -1);
      

      然后它直接为第二个查询做好准备,这将需要一个 NOT IN:

      select * from table where item NOT IN ($array)
      

      请注意,最好使用准备好的语句而不是 mysqli_real_escape_string,但在这种情况下应该没问题,因为 $namelist 已经直接来自您的数据库。

      【讨论】:

        猜你喜欢
        • 2015-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-06
        • 1970-01-01
        • 1970-01-01
        • 2015-01-25
        • 2012-10-15
        相关资源
        最近更新 更多