Skip to content
Advertisement

PHP MYSQL $row[$variable]

I am trying to work around with dynamic table creation and data fetching. I am trying to get the data using following code :

    $myQuery = "SELECT ".$col_name." FROM ".$tabname." WHERE sampleid='".$sid."'";
    $result = mysql_query($myQuery);
    $row = mysql_fetch_array($result);
    echo "<br>".$row['$col_name'];

But, I am unable to get any data back. I checked printing the query and running it in php my admin and its working as I want. But I guess variable in array might not be working I guess. Please help me regarding the same. Thanks.

The Whole loop looks something like this :

$myQuery = "SELECT * FROM information_schema.columns WHERE table_name = '$tabname'";
$re = mysql_query($myQuery);

while($row = mysql_fetch_array ($re)){
         if(!empty ($row)){
                    $col_name = $row['COLUMN_NAME'];

          $myQuery = "SELECT ".$col_name." FROM ".$tabname." WHERE sampleid='".$sid."'";
                    echo "<br>".$myQuery;
                    $reqq = mysql_query($myQuery);
                    $roww = mysql_fetch_array($reqq);
                    echo "<br>".$roww[$col_name];

                    }
                }

Advertisement

Answer

You are fetching an array, not an assoc array. Use this:

echo "<br>".$row[0];

Edit: Having looked a little more, this may not be correct. You can set fetch_array to return assoc arrays.

You cannot parse variables through single quotes ‘

echo $row['col_name'];  // manually typed string.

or

echo $row[$col_name];

or

echo $row["$col_name"];
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement