PHP MYSQL $row[$variable]

 ̄綄美尐妖づ 提交于 2019-12-10 10:17:14

问题


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:


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



回答2:


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




回答3:


Have you tried looping through the results array as such:

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



回答4:


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


来源:https://stackoverflow.com/questions/11752333/php-mysql-rowvariable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!