-2

here is my code. I want to set the value of checkbox to be the value I am fetching from the database.

while($row=mysql_fetch_array($result2))
{
    $n=$row['name'];
    echo '<input type="checkbox" name="chkbox[]" value=$row["name"]>';
    echo $n."<br>";
    $i++;
}

More clearly, I am using a query to get 'names' from a database column and I have to use those names as values for consecutive checkboxes.

Maybe I am not able to explain my problem. I will try again. Suppose I have a variable $var="abc". I want to use $var as a value for a checkbox as in;

<type="checkbox" name="pqr" value='$var'>

In nutshell this is what I want to do, but its not working.

potashin
  • 44,205
  • 11
  • 83
  • 107
user3734204
  • 3
  • 1
  • 4
  • 1
    Please at least try something before asking a question. A list of requirements is not a question. – Anonymous Jun 12 '14 at 13:26
  • What exactly isn't working? What have you tried changing? – Ynhockey Jun 12 '14 at 13:26
  • What in your database tells you that it was selected? – RiggsFolly Jun 12 '14 at 13:50
  • @Notulysses: nope. I have tried to explain my problem more clearly through the edit. please see if you can help. ty – user3734204 Jun 12 '14 at 13:51
  • @user3734204 : Have you got any errors in the error log?Have you checked if data set retrieved from the database is not empty? Information that you've provided can't specify the problem, it is still too broad. And also : what exactly is wrong with your code?In other words : are checkboxes displayed or not displayed at all(skipping while - empty data set) or problem is just with setting the value attribute? – potashin Jun 12 '14 at 13:54
  • What output do you have right now ?[Here is an example with the defined variable that is working fine and as expected](https://eval.in/161643) – potashin Jun 12 '14 at 14:01
  • 1
    @Notulysses: got it. Your answers were correct and are working. thank you – user3734204 Jun 12 '14 at 14:09
  • possible duplicate of [Interpolation (double quoted string) of Associative Arrays in PHP](http://stackoverflow.com/questions/4738850/interpolation-double-quoted-string-of-associative-arrays-in-php) – Sergiu Paraschiv Jun 12 '14 at 14:12

2 Answers2

3

You can concatenate the value retrieved from the database with the html string like it is shown below :

echo '<input type="checkbox" name="chkbox[]" value="' . $row["name"] . '">';

Or interpolate variable using double quotes for string definition and single quotes for input attributes :

 echo "<input type='checkbox' name='chkbox[]' value='{$row["name"]}'>";
potashin
  • 44,205
  • 11
  • 83
  • 107
0

You are actually just missing some quotation marks and a few . to concatenate:

while($row=mysql_fetch_array($result2))
{
    $n=$row['name'];
    echo '<input type="checkbox" name="chkbox[]" value="'.$row["name"].'">';
    echo $n."<br>";
    $i++;
}
neelsg
  • 4,802
  • 5
  • 34
  • 58