Mysql PDO: get a string with "dynamic" fields in a query

I have a request with a dynamic field, how can I access this field without knowing its name?

define('FIELD_NAME',"name"); $stmt = $connexion->query('SELECT '.FIELD_NAME.' from mytable); while ($rs=$stmt->fetch(PDO::FETCH_OBJ)){ echo $rs->FIELD_NAME; // DOESN'T WORK echo $rs->name; // WORK } 
+8
php mysql pdo fetch row
source share
4 answers

Wrap the constant in {} to create dynamic variables.

 echo $rs->{FIELD_NAME}; 

You can see an example from the documentation .

You can also use curly braces to clearly distinguish the property name.

Demo: http://3v4l.org/sgvV4

+3
source share

There are many approaches to this. If it is not important that the variable name matches the name column_name, you could assign an alias to the expression in the SELECT

For example:

  SELECT whateverexpression AS mycol FROM mytable LIMIT 1; 

Then you “know” the name of the variable in the $mycol object

  echo $rs->mycol; 

I think this approach may be good in the more general case when you are dealing with tables with column names that were assigned by syphilitic idiot developers who had a good reason for

 CREATE TABLE t (`Hey!$I (can)^name.\my->column Wh@tever` INT); INSERT INTO t VALUES (42); SELECT `Hey!$I (can)^name.\my->column Wh@tever` FROM t; 

Obviously, there are many other approaches, for example, instead of PDO::FETCH_OBJ and using PDO::FETCH_NUM . If you want to stick with PDO::FETCH_OBJ , I think the alias assignment will work.

Getting metadata from a result set is an approach I would consider if getColumnMeta was not yet experimental.

+3
source share
 define('FIELD_NAME',"name"); $stmt = $connexion->query('SELECT '.FIELD_NAME.' from mytable'); while ($rs=$stmt->fetch(PDO::FETCH_NUM)){ echo $rs[0]; } 

Using this approach, if FIELD_NAME is defined by something like *, you can still get the first column.

+1
source share

If you are trying to get only one value from each row, you can use PDOStatement::fetchColumn()

 define('FIELD_NAME',"name"); $stmt = $connexion->query('SELECT '.FIELD_NAME.' from mytable'); while ($col = $stmt->fetchColumn()) { echo $col; } 

Also note: you are missing. '

0
source share

All Articles