Skip to content
Advertisement

Assign value PHP variable as column name during fetching

I am trying to fetch the values from columns in a MySQL table using PHP. The variable $batch_id is dynamic, i.e. it changes column name depending on the request. Say, it can adopt value like ‘Batch1’ or ‘Batch10’. I was able to extract the column name into the $batch_id variable, but when I am passing the column name, say ‘Batch10’ the array $batch_Value is populated with ‘Batch10’ rather than the values of that column. I am sure there must be a simple solution, but I am stuck. Any help will be appreciated. I am using the following code.

$batch_Value = array();
if($num>0){
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row);
        $batch_Value[] = $batch_id;
    }
}

enter image description here

On the left what I am getting and on the right is the expected outcome. But right hand one I am getting when I am using the Column name directly

Advertisement

Answer

Fetch the data as number-indexed array instead of associative one. Also, don’t use extract, it’s unsafe because it can overwrite existing variables.

$batch_Value = array();
if($num>0){
    while ($row = $stmt->fetch(PDO::FETCH_NUM)){
      $batch_Value[] = $row[0];
    }
}

Or if the desired column is not the first one, then you can find the value in the $row array (which is an associative one, see print_r($row); for details about it), with the following:

$batch_Value = array();
if($num>0){
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
      $batch_Value[] = $row[$batch_id];
    }
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement