Jump to content

handling a radio button name(array) from a form


imohiddin

Recommended Posts

hi,

im making a website for my final year project, and im having some trouble. im making a voting site that uses the single transferable vote method. im new to php as well.
basically, im having trouble handling radio buttons made in another script. the problem i have is that i've set the name of each set of radion button as the name of the candidate, and this is done by using a for loop and an array( ass you can see in the code below)

[code]echo '<form action="registervote.php" method="post">';
echo '<table align="center" cellspacing="50" cellpadding="5" border="2">';
echo '<tr>';
for($i=1; $i<=$num; $i++)
{
    $arr1=mysql_fetch_array($result, MYSQL_ASSOC);
    echo '<th align="center" bgcolor="yellow">' . $arr1['name'] . '</th>';

    while(!$i)
    {
       echo '</tr><tr>';
    }

    for($j=0; $j<=$num; $j++)
   {
  echo '<td align="center">'.($j+1).'<input type="radio" name="'.$arr1['name'].'" value="'($j+1).'"/></td>';
   }
  echo '</tr>';
   }

echo '</table>';

echo '<p><br /><center/><input type="submit" name="submit" value="VOTE!" /></p>';
echo '<input type="hidden" name="submitted" value="TRUE" />';[/code]

the handling script is below, what i need it to do is to confirm that an input has been selected(then i can add the input value into my MySQL database table):

[code]if(isset($_POST['submitted']))
{

    if(isset($_POST['']))
    {
        echo '<p>input has been selected</p>';
    }
    else
        {
            echo 'no input';
        }

} [/code]

what i haven't been able to figure out for two days is what i should write in the $_POST[] array to handle the radio button. all the radio buttons would have their names set as the candidate name in the ballot that they would be taking part in. so i cant just set each set of radio buttons' name as the name of each candidate manually, as these can change for each ballot. i dont know how to check if the name of the radio button(which is an array) has been set, using the isset() function. please help.
Link to comment
Share on other sites

I'm not sure you understand how radio buttons work:

1) If you have a group of radio buttons, they all have the same name.
2) The value of the one that is selected will be passed as the result.

<input type="radio" name="asdf" value="1">blah
<input type="radio" name="asdf" value="2">blah
<input type="radio" name="asdf" value="3">blah
<input type="radio" name="asdf" value="4">blah

<input type="radio" name="lkjh" value="1">blah
<input type="radio" name="lkjh" value="2">blah
<input type="radio" name="lkjh" value="3">blah
<input type="radio" name="lkjh" value="4">blah

Then in the post, you'll have $_POST['asdf'] and $_POST['lkjh'] with a value between 1 and 4.

If that doesn't clear it up, please rephrase your question.

I think your problem is that you're putting the array value as the name instead of the value.
Link to comment
Share on other sites

thank you for your reply ober,

sorry i didnt make clear my question. basically, i have a few candidates in a ballot. so each candidate will have his own group of radio buttons. the name of each candidate's group will be set as his/her name but the values will be different as you can see below and in the html source i've also included.

[code]<input type="radio" name="Wayne Rooney" value="1"/>
<input type="radio" name="Wayne Rooney" value="2"/>
<input type="radio" name="Wayne Rooney" value="3"/>
<input type="radio" name="Wayne Rooney" value="4"/>[/code]

the voter will select a number(for this example, 1 to 4). so what im having trouble with is what to write in the $_POST, so that the script checks which candidate's radio button has been selected.
i can't manually set the name of each candidate because each ballot will have different candidates, so the names would be different and thats the reason i have set the name of each candidate in the for loop as:

[code]name="'.$arr1['name'].'"[/code]

$arr1 is defined as:

[code]$arr1=mysql_fetch_array($result, MYSQL_ASSOC);[/code]

so the name of each radio button will be the name of each candidate because $result is set thus:

[code]$query="SELECT CONCAT(candidate_Fname, ' ', candidate_Sname) AS name FROM candidates";
$result=@mysql_query($query);[/code]

also $num is:

[code]$num=mysql_num_rows($result);[/code]


below is the html source for the page:

[code]<form action="registervote.php" method="post"><table align="center" cellspacing="50" cellpadding="5" border="2"><tr><th align="center" bgcolor="yellow">Wayne Rooney</th><td align="center">1<input type="radio" name="Wayne Rooney" value="1"/></td><td align="center">2<input type="radio" name="Wayne Rooney" value="2"/></td><td align="center">3<input type="radio" name="Wayne Rooney" value="3"/></td><td align="center">4<input type="radio" name="Wayne Rooney" value="4"/></td></tr><th align="center" bgcolor="yellow">John Smith</th><td align="center">1<input type="radio" name="John Smith" value="1"/></td><td align="center">2<input type="radio" name="John Smith" value="2"/></td><td align="center">3<input type="radio" name="John Smith" value="3"/></td><td align="center">4<input type="radio" name="John Smith" value="4"/></td></tr><th align="center" bgcolor="yellow">Eric Cantona</th><td align="center">1<input type="radio" name="Eric Cantona" value="1"/></td><td align="center">2<input type="radio" name="Eric Cantona" value="2"/></td><td align="center">3<input type="radio" name="Eric Cantona" value="3"/></td><td align="center">4<input type="radio" name="Eric Cantona" value="4"/></td></tr><th align="center" bgcolor="yellow">Cristiano Ronaldo</th><td align="center">1<input type="radio" name="Cristiano Ronaldo" value="1"/></td><td align="center">2<input type="radio" name="Cristiano Ronaldo" value="2"/></td><td align="center">3<input type="radio" name="Cristiano Ronaldo" value="3"/></td><td align="center">4<input type="radio" name="Cristiano Ronaldo" value="4"/></td></tr></table><p><br /><center/><input type="submit" name="submit" value="VOTE!" /></p><input type="hidden" name="submitted" value="TRUE" />[/code]

i hope that i've made it clearer now and apologies for how long this is. i look forward to your reply.thnx again.
Link to comment
Share on other sites

Alright... that makes a little more sense.

However, might I suggest a slight modification? I assume you have IDs associated with each candidate, correct? I'd suggest using the IDs as the names instead of the candidate names because you're going to run into issues with spaces being converted in the URL and so on and so on.

Beyond that, I also suggest the following:

Name your radio button groups like this:
[code]<input type="radio" name="candidate_'.$arr1['ID'].'" value="1"/>[/code]

Then in your processing, use a simple foreach loop to pull those out and manage them seperate from your other form elements (if there are any):
[code]foreach($_POST as $key => $val)
{
     if(substr($key,0,10) == 'candidate_')
     {
          $id = substr($key,11);
          // run query to get name from ID
          echo "candidate x has been given a rating of $val";
     }
}[/code]

Does that help?
Link to comment
Share on other sites

thank you for your reply once again ober,

i really appreciate your suggestion and it has helped so far. i am however having some issues again(you can see im a beginner). this time it is with the printing of the candidates' names where you have suggested

[code]echo "candidate x has been given a rating of $val";[/code]

i am having trouble getting it to print the names of [i]each[/i] candidate where you have written 'candidate x'.

this is the code that i'm trying to write:

[code]if(isset($_POST['submitted']))
{

   foreach($_POST as $key => $val)
   {
      if(substr($key,0,10) == 'candidate_')
      {
          $id = substr($key,11);
          require_once('./mysql_connectevote1.php');
         $query="SELECT CONCAT(candidate_Fname, ' ', candidate_Sname) AS name FROM candidates WHERE candidateID='$id'";
            
           $result=mysql_query($query);
          
            while($row=mysql_fetch_array($result, MYSQL_ASSOC))
            {
    //run query to get name from ID
    echo "".$row['name']." has been given a rating of $val <br/>";

            }

       }
    }

} [/code]

$row['name'] keeps printing the name of another candidate(who will be in another ballot) instead of printing the name of each candidate in this ballot. i think its to do with loops or something.
your help and suggestions/modifications is greatly appreciated in this.
Link to comment
Share on other sites

My math may be a little off.

Try changing this:
$id = substr($key,11);

To this:
$id = substr($key,10);

Or just play around with that to make sure you're getting the entire ID out of the POST variable. Also, you can remove the while loop since you should only have to call that mysql_fetch line once.
Link to comment
Share on other sites

thnx for your latest reply,

i think that i haven't made myself clear again. my question is how can i make it give me something like:

" Wayne Rooney has been given a rating of 1"

instead of:

" candidate x has been given a rating of 1"

at the moment it is giving me the value of $val, but not the candidates' name.
if i need to write another mysql query, do u think that u could tell me what i need to write please?

thanx for your help.

sorry mate,

it's working now! i didnt follow your instructions properly. i changed it to $id=($key, 10) and its working now.

i really appreciate all the help you've given me and i couldn't have got on with my work without your help.

thank you again.

ps:- if i have more problems with this project should i post it in this thread or another?
Link to comment
Share on other sites

sorry again,

just (hopefully) one last thing...how can i stop voters ranking two(or more) candidates with the same ranking. e.g. giving both 'wayne rooney' and 'eric cantona' a ranking of 1.
can i do this at the form level or does it have to be done in the form-handling script?

thanks once more.
Link to comment
Share on other sites

A few months ago, someone else asked a similar question and I came up with the following code:
[code]<?php
$err_style = array();
$radio_sylye = array();
if (isset($_POST['submit'])) {
    $unique_opts = array_unique($_POST['opt']);
    for ($i=1;$i<17;$i++)
        if (!isset($unique_opts[$i])) {
            $err_style[$i] = ' style="color:red;font-weight:bold;"';
            $radio_style[$i] = ' style="background-color: red';
        }
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <title>Ranking Test</title>
    <style type="text/css" media="screen">
    .row {
        clear:both;
        display:block;
        height:1.5em;
        width:100%;
    }
    .label {
        display:block;
        float:left;
        width:5em;
    }
    .header {
        float:left;
        display:block;
        height:1.5em;
        width:2em;
        text-decoration:underline;
        font-weight:bold;
    }
    .radiob {
        float:left;
        display:block;
        height:1.5em;
        width:2em;
    }
    .sub {
        clear:both;
        float:left;
        display:block;
        margin-top:0.25em;
    }
    .red {
        color: Red;
    }
    
    .bold {
        font-weight: bold;
    }
    
    hr {
        clear: both;
    }
    </style>
</head>

<body>
<form method="post">
<div class="row"><span class="label">&nbsp;</span>
<?php
for ($i=1;$i<17;$i++)
    echo '<span class="header">' . $i . '</span>';
echo '</div>'."\n";
for ($row = 1; $row < 17; $row++) {
    echo '<div class="row"><span class="label"';
    if (isset($err_style[$row])) echo $err_style[$row];
    echo '>Item #' . $row . ':</span>';
    for ($opt = 1; $opt < 17; $opt++) {
        echo '<span class="radiob"';
        if (isset($_POST['opt'][$row]) && $_POST['opt'][$row] == $opt && isset($radio_style[$row])) echo $radio_style[$row];
        echo '">';
        echo '<input type="radio" id="opt_' . $row . '_' . $opt . '" name="opt[' . $row . ']" value="' . $opt . '"';
        if (isset($_POST['opt'][$row]) && $_POST['opt'][$row] == $opt) {
            echo ' checked="checked"';
        }
        echo '></span>'; }
    echo "</div>\n";}
?>
<div class="sub"><input type="submit" name="submit" value="Submit Rankings"></div>
</form>
<?php
if (isset($_POST['submit'])) {
    echo '<hr>';
    if (count($_POST['opt']) != 16) echo "<p class='red'>You didn't rank all of the items, try again</p>\n";
    else {
        $unique_opts = array_unique($_POST['opt']);
        if (count($unique_opts) != 16) {// duplicate ranking found
            $tmp = array();
            for ($i=1;$i<17;$i++){
                if (!isset($unique_opts[$i])) $tmp[] = $i.'<span class="bold">(Rank: ' . $_POST['opt'][$i] . ')</span>';
            }
            echo 'The rankings of the following Items were already used: ' . implode(', ',$tmp) . '<br>';
        }
    }
}
?>
</body>
</html>[/code]

Look at the code -- see it in action at <[a href=\"http://www.rbnsn.com/phpfreaks/ranking.php\" target=\"_blank\"]http://www.rbnsn.com/phpfreaks/ranking.php[/a]>

Have fun... :-)

Ken
Link to comment
Share on other sites

thanks for your reply ken,

its just the kind of thing i was looking for. im gonna have a look and try to implement it into my site. however, do you think that you could have a look at my coding(from previous threads) and see how i can make the rankings not the same for two or more candidates.

your help is appreciated.
Link to comment
Share on other sites

hey guys,

anybody know how i should change my coding(see above) to make my script act like ken's one? i.e. no ranking can be repeated for two or more candidates.
please take into account my coding so far and that i am using it with mysql where i have a table named 'votes' with columns voter_id, candidateID, election, rank...where election is the election ballot that the candidate will be taking part in.

cheers
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.