3

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];

                    }
                }
1
  • 2
    In between the first two lines there can you do an echo $myQuery; and put the response here? Also maybe the results from var_dump($row); Commented Aug 1, 2012 at 3:55

4 Answers 4

8

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"];
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks That worked quite well. The last option worked right. Thank you so much !
3

You tried that->

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

OR

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

Cause like said @Fluffeh it's not a associative array

Comments

0

Have you tried looping through the results array as such:

while($row = mysql_fetch_array($result)) {
echo $row['col_name'];
echo "<br />";
}

Comments

0

I would suggest the following solution. Give the parameter $col_name and AS Col_Name Then the $row['Col_Name'] can always be set to the parameter no matter what the value.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.