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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.