Jump to content

$row[ variable here? ]


xcandiottix

Recommended Posts

To claify this a little better here's my table:

ID | 1 | 2 | 3

1 | red | green | blue

 

I want to echo out: red, green, blue. But the number of columns later on maybe become bigger:

 

ID | 1 | 2 | 3 | 4 | 5

1 | red | green | blue | orange | black

 

So I need any $row calls to anticipate this...

mysql_connect()
mysql_select_db()
$query = "Select * FROM table WHERE ID = 1";
$result = mysql_query($query);

$i = 1;
for($x = 0; $x < $i; $x++){
$row = mysql_fetch_assoc($result);
if($row[$x] !== ""){
echo "Color".$x."=".$row[$x];
$i++;
}
}

 

The problem is I can't seem to get $row to work with a variable with in the brackets ... not sure if anyone can spot a work around. 

 

As a side note, if I change

 

echo "Color".$x."=".$row[$x];

 

to

 

echo "Color".$x."=".$row['1'];

 

then I get "Color1=red Color2= Color3= etc" echoed. So it works ... the var is hanging up it seems.

 

Link to comment
https://forums.phpfreaks.com/topic/214070-row-variable-here/#findComment-1113952
Share on other sites

$row is an associative array in your case.

 

Your best off using a foreach.

 

mysql_connect()
mysql_select_db()
$query = "Select * FROM table WHERE ID = 1";
if ($result = mysql_query($query)) {
  if (mysql_num_rows($result)) {
    while ($row = mysql_fetch_assoc($result)) {
      foreach ($row as $k => $v) {
        echo "Color $k = $v<br />";
      }
    }
  }
}

Link to comment
https://forums.phpfreaks.com/topic/214070-row-variable-here/#findComment-1113954
Share on other sites

Oh, and if your only expecting one result, you don't need the while....

 

mysql_connect()
mysql_select_db()
$query = "Select * FROM table WHERE ID = 1 LIMIT 1";
if ($result = mysql_query($query)) {
  if (mysql_num_rows($result)) {
    $row = mysql_fetch_assoc($result);
    foreach ($row as $k => $v) {
      echo "Color $k = $v<br />";
    }
  }
}

Link to comment
https://forums.phpfreaks.com/topic/214070-row-variable-here/#findComment-1113955
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.