简体   繁体   中英

Fetch specific column in query

I have this PHP code to fetch the data of a query.

$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. Help would be appreciated.

Look at the array_column () function. It is specifically for things like this.

To get the list of 'min_date' values of all recors:

$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

$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.

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

Assuming min_date is the first column in the SQL query table.

EDIT: optimal way:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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