Storing retrieved data into a variable

Hello,

I’m trying to send data with a form in a hidden input field whose value is retrieved from a database.

while ($row = mysql_fetch_array($result)) {
echo ‘Value:’ . $row[‘value’] . ‘<br><br>’;
}

How would I store the value in ‘$row[‘value’]’ so it can passed by a form.

I tried this:

<input type=“hidden” name=“’ . $row[‘value’] . '”>

But it doesn’t work. It’s always empty. I figure I have to store ‘$row[‘value’]’ into a variable first like this:

$row[‘value’] = $value;

However that doesn’t work either. It’s still empty.

Your help is much appreciated. :slight_smile:

There are a few things wrong with your code.

First, is ‘value’ the name of a column if your database? Does it actually have data in that column in a row? Seeing your database structure would be helpful.

Second, because “while” is a loop, it will rewrite the value of “$row[‘value’]” each time it repeats. If the value of “value” for the last row is empty, your variable will be empty. Additionally, typing $row[‘value’] anywhere below your loop will only return the value of the LAST row returned in your results.

Third, how many rows are returned?

Fourth, doing $row[‘value’] = $value will set $row[‘value’] to equal whatever $value equals - which I’m guessing is nothing at this point. If should be flipped. $value = $row[‘value’]. However, $value will still only be equal to the ‘value’ column of the LAST row returned.

Do this:


while ($row = mysql_fetch_array($result)) {
print_r($row['value']);
}

What does that output?

I suspect you only need to do mysql_fetch_assoc, instead of mysql_fetch_array - which returns both numerical and associative arrays.

If hidden field is inside the loop, i think it should work:

while ($row = mysql_fetch_array($result)) {
   echo '<input type="hidden" name="' . $row['value'] . '">'
}

While that will work, what you are doing is creating a hidden variable, whereby the name is the value. What you should be doing is:

while ($row = mysql_fetch_array($result)) {
   echo '<input type="hidden" name="myHiddenvar' . $i++ . '" value="' . $row['value'] . '">'
}

What you are doing is the equivelent of creating a variable called $3.154 when infact you should be creating a variable called $pie and assigning it a value of $3.154. While it will work, it makes accessing the variable very difficult as you wont know what its name is going to be.

PHPycho: i quoted your post as the code was more correct, I appreciate the original html came from the OP.

I would do something like this with array for easy access while submitting the form.


while ($row = mysql_fetch_array($result)){ 
	echo '<input type="hidden" name="myField[]" value="' . $row['value'] . '">' . "\
";
}

So that I can get in submitted page as :


print_r($_POST['myField']);

Interesting, I didnt know you could use an array in html. Thanks.

Thanks a lot guys. Figured it out. Cheers!