简体   繁体   English

获取查询中的特定列

[英]Fetch specific column in query

I have this PHP code to fetch the data of a query. 我有这个PHP代码来获取查询数据。

$result = $stmt->fetchAll();

The result is: 结果是:

array(1) (
  [0] => array(2) (
    [min_date] => (string) 2017-04-27
    [0] => (string) 2017-04-27
  )
)

I just need to fetch the min_date value. 我只需要获取min_date值。 Help would be appreciated. 帮助将不胜感激。

Look at the array_column () function. 查看array_column ()函数。 It is specifically for things like this. 它专门用于这种事情。

To get the list of 'min_date' values of all recors: 获取所有记录的“ min_date”值列表:

$min_dates = array_column($result, 'min_date');

To only get the first one: 仅获得第一个:

$min_date = $result[0]['min_date'];

But if there are no records returned from the query it will result in an error, so if that can happen do this instead 但是,如果查询没有返回记录,则会导致错误,因此,如果发生这种情况,请改为执行此操作

$min_date = isset($result[0]['min_date'])?$result[0]['min_date']:'not_found';

to get (string)'not_found' if there are no results or 如果没有结果则获取(string)'not_found'或

$min_date = isset($result[0]['min_date'])?$result[0]['min_date']:false;

to get (bool)false. 弄虚作假。 You get the idea. 你明白了。

All you need to do is add the PDO::FETCH_COLUMN arguement. 您需要做的就是添加PDO :: FETCH_COLUMN争论。

$min_date = $stmt->fetchAll(PDO::FETCH_COLUMN, 0)[0];

Assuming min_date is the first column in the SQL query table. 假设min_date是SQL查询表中的第一列。

EDIT: optimal way: 编辑:最佳方法:

$min_date = $stmt->fetch(PDO::FETCH_COLUMN, 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM