Jump to content

Checkboxes


rghayes

Recommended Posts

I am designing a voting webpage where in users can choose multiple values and all are submitted to a mysql database. I am using checkboxes. I can get one value to go in great, but its the mutiple value thing that has me pulling my hair out. Can someone PLEASE help a beginner out??

Link to comment
Share on other sites

Add

, <br>;

aftr the echo part to view choices on lines

And then run an array sending value by value to the db

If u want all values to be sent as a string, concatenate them into one string separated by , and then send the stribg itself

Link to comment
Share on other sites

Well, as Barand said you have to tell us about your database structure, so I wrote a simple example how to insert multiple radio values to database.

 

In this example I'm going to use Barand's example.

 

You can take a look that thread too - http://forums.phpfreaks.com/topic/267013-looping-multiple-rows-into-database/

<?php
if(!empty($_POST['Submit'])) {
   
$votes = $_POST['myvote'];


// build a query string .....
$sql = "INSERT INTO `tbl_name`(`votes`) VALUES";

    foreach ($votes as $vote) {
        
    $sql .= "(".$vote;
    // trim the last comma from a query string in case you have multiple values
    //$sql = rtrim($sql, ',');
    
    $sql .= "),";
    }
    
// trim the last comma from a query string
$sql = rtrim($sql, ',');

//echo '<pre>' . print_r($sql, true) . '</pre>';

}


?>
<form method="post">
    
    <input type="checkbox" name="myvote[]" value="1" />

    <input type="checkbox" name="myvote[]" value="2" />

    <input type="checkbox" name="myvote[]" value="3" />
    
    <input type="submit" name="Submit" value="Go!" />
</form>

Results:

 


INSERT INTO `tbl_name`(`votes`) VALUES(1),(3)
Edited by jazzman1
Link to comment
Share on other sites

OK, my database just has entries for each choice represented by each check box and I need to keep up with how many times an item is voted on.

 Well, I think it's time to show us what you've done so far ;)

Link to comment
Share on other sites

Ok here is my PHP.  I think my biggest problem now is I need to update the count in the db not really add anything

 

 

 

<?php 
 $vote=$_POST['vote'];
 
 
 
$tstring = implode(',' , $vote); echo $tstring; 
 
$con = mysql_connect("localhost","root","YES");
if (!$con) 
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("poll", $con);
//insert to the table
$sql="update poll_results
            set num_votes = num_votes + 1
            where candidate = '$tstring'";
if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "CheckBox value succesfully added";
mysql_close($con)
?>
Link to comment
Share on other sites

Try,

$vote = $_POST['vote'];

$tstring = implode(',', $vote);

$sql="update `poll_results`
            set `num_votes` = `num_votes` + 1
            where candidate IN ('".$tstring."')";
Edited by jazzman1
Link to comment
Share on other sites

Only one table with 2 columns. First column is the name of what is being voted for and the second column keeps up with the number of votes. This is what I think is giving me such a hard time, all I need to do is update the number of votes in the db not really add data.

Link to comment
Share on other sites

So, my fault.

 

Try this and give me back the result of the echo, because I'm not using my machine:

$vote = $_POST['myvote']; 

$tstring = implode(',',array_map('mysql_real_escape_string', $vote));

$sql="update `poll_results`
            set `num_votes` = `num_votes` + 1
            where candidate IN ($tstring)";

echo $sql;
Edited by jazzman1
Link to comment
Share on other sites

This is what was returned on submit:

 

Notice: Undefined index: myvote in C:\xampp\htdocs\belltion\show_poll.php on line 2

Warning: array_map(): Argument #2 should be an array in C:\xampp\htdocs\belltion\show_poll.php on line 4

Warning: implode(): Invalid arguments passed in C:\xampp\htdocs\belltion\show_poll.php on line 4
update `poll_results` set `num_votes` = `num_votes` + 1 where candidate IN ()

Edited by rghayes
Link to comment
Share on other sites

Only one table with 2 columns. First column is the name of what is being voted for and the second column keeps up with the number of votes. This is what I think is giving me such a hard time, all I need to do is update the number of votes in the db not really add data.

 

A lot easier to store

 

userid | vote

 

where vote is the checkbox value. If they vote for 3 items, write 3 records (one for each)

 

All you have to do later is query the db to get the counts

 

 

SELECT vote, COUNT(*) as total
FROM votes
GROUP BY vote
ORDER BY total DESC
Link to comment
Share on other sites

The correct sql string should be - update `poll_results` set `num_votes` = `num_votes` + 1 where candidate IN ('TomJo','AlJac','AmyThom','ArthurBo','BillyMid','KarenMil');

I'm not at home right now, I am going to create later if I have a time ;)

Edited by jazzman1
Link to comment
Share on other sites

Barand is right!

 

Going back to the query above and the implode function try this, not tested but.... I think is going to be correct:


$vote = $_POST['vote']; 

$tstring = "'" . implode("', '", array_map('mysql_real_escape_string', $vote)) . "'";

$sql="UPDATE `poll_results`
            SET `num_votes` = `num_votes` + 1
            WHERE `candidate` IN ($tstring)";

echo $sql;
Link to comment
Share on other sites

I still am still  struggling with this but please check out my updated code. After some serious research I found this but I keep getting Fail to add test_value.

 

 

if (!$db_conn = new mysqli('localhost', 'root', 'YES', 'charity_db'))
{
  echo 'Could not connect to db<br />';
  exit;
}
 
if(isset($_POST["vote"])) 
{$vote = $_POST["vote"];} 
else {$vote=array();}
 
for ($i="0"; $i<count($vote); $i++) { 
if(!is_numeric($vote[$i])) {$vote[$i]="";} 
if(empty($vote[$i])) {unset($vote[$i]);}}
 
$vote = implode ("<>", $vote); 
$vote = "<>".$vote.""; 
$sql = "INSERT INTO data_tbl (`id`, `choice`) VALUES (NULL, '$vote')"; 
$res=mysql_query($sql) or die ("Fail to add test_value");
 
$sql = "select id, choice from data_tbl limit 1"; 
$res=mysql_query($sql) or die ("Fail to get test"); 
$test = explode('<>',$pres[1]); 
for ($i="0"; $i<count($vote); $i++) { 
if(empty($vote[$i])) {unset($vote[$i]);} }
 
?>
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.