Jump to content

Not all quieries from form checkboxes are not being executed


Go to solution Solved by Psycho,

Recommended Posts

I have a form with several (9) checkboxes that are part of a association vote. The user can vote (select) up to 4 checkboxes of which the results (votes) are then recorded in database. The form is processed as:

if ($_POST['vote'] == 'Juste'){
	$result = mysqli_query($db,"UPDATE NewBoard SET votes=votes+'1' WHERE lname = 'Juste'")or die ("Fatal Query Error: " . mysqli_error($db)); 
	}
	if ($_POST['vote'] == 'Chavez-Gris'){
		$result = mysqli_query($db,"UPDATE NewBoard SET votes=votes+'1' WHERE lname = 'Chavez-Gris'")or die ("Fatal Query Error: " . mysqli_error($db)); 
	}
etc (for all 9 entries)

My problem is that only the last checked box gets recorded. If I check both the checkboxes above (both if statements would be true), only the Chavez-Gris is recorded. Need all checked checkboxes recorded not just the last one.

Any help and wisdom would be greatly appreciated. Thanx

 

 

Link to comment
Share on other sites

  • Solution

As @dodgeitorelse3 asks, please show your form code. It is impossible for a single variable (e.g. $_POST['vote']) to have multiple values. I am assuming you have nine checkboxes all with the same name, but different values. That won't work. You need to either create them with different names OR create them as an array. Also, checkboxes are unique in that if they are not checked they are not included in the POST data, so you would want to check that they are set and not just check for the values.

If you name each checkbox differently (the value would be unnecessary in this context)

<input type="checkbox" name="Juste" value="1"> Juste
<input type="checkbox" name="Chavez-Gris" value="1"> Chavez-Gris

Then your processing code might look like this

if (isset($_POST['Juste'])) {
    $result = mysqli_query($db,"UPDATE NewBoard SET votes=votes+'1' WHERE lname = 'Juste'")or die ("Fatal Query Error: " . mysqli_error($db)); 
}
if (isset($_POST['Chavez-Gris'])) {
    $result = mysqli_query($db,"UPDATE NewBoard SET votes=votes+'1' WHERE lname = 'Chavez-Gris'")or die ("Fatal Query Error: " . mysqli_error($db)); 
}

Or you could create your checkboxes as an array (this would be my approach)

<input type="checkbox" name="votes[]" value="Juste"> Juste
<input type="checkbox" name="votes[]" value="Chavez-Gris"> Chavez-Gris

In which case the processing code might look like this

//Set variable based on POST value or empty array if none selected
$votesArray = isset($_POST['votes']) ? $_POST['votes'] : array();

//Check for each value in the $votesArray
if (in_array('Juste', $votesArray)) {
    $result = mysqli_query($db,"UPDATE NewBoard SET votes=votes+'1' WHERE lname = 'Juste'")or die ("Fatal Query Error: " . mysqli_error($db)); 
}
if (in_array('Chavez-Gris', $votesArray)) {
    $result = mysqli_query($db,"UPDATE NewBoard SET votes=votes+'1' WHERE lname = 'Chavez-Gris'")or die ("Fatal Query Error: " . mysqli_error($db)); 
}

 

Link to comment
Share on other sites

while your current problem has been addressed above, you should not write out code for every possible data value. this is an error prone waste of your time typing. if you had 30 or a 100 of these, does it seem like it would be a good idea to sit at a computer creating 9, 30, or 100 sets of code that only differs in the value they use?

you need to use a data driven design instead, where you have a data structure (array, database table) that defines the expected values. you would then loop over this defining data to produce the html makeup, validate the input data, and perform the processing, letting the computer do this repetitive work for you. because your database table already defines the choices, you should just query it to get the choices to use in the code.

here are some other points for the posted code -

  1. you should actually be using ids for the submitted values, rather than the actual name.
  2. don't use or die() for error handling, ever. as of php8, the msyqli extension uses exceptions for errors and any existing conditional logic in your code testing for errors won't get executed upon an error since execution transfers elsewhere. so, remove any existing database statement error handling logic. the only time you should catch and handle database exceptions in your code are for duplicate or out of range user entered data. for this assignment, this is not user entered data, simply do nothing in your code for database error handling.
  3. you need to use a prepared query.
  4. don't put quotes around numbers.

 

here's example code showing how to dynamically do this using a data driven design -

// since i don't have your database, this example uses an array to define the choices
// you would query the database table instead
$choices = ['Juste','Chavez-Gris'];

// examine the submitted data
echo '<pre>'; print_r($_POST); echo '</pre>';

// post method form procesing
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
	foreach($choices as $choice)
	{
		if(in_array($choice,$_POST['vote']??[]))
		{
			$sql = "UPDATE NewBoard SET votes=votes+1 WHERE lname = '$choice'";
			mysqli_query($db,$sql);
		}
	}
}


// html document
?>

<form method='post'>
<?php
foreach($choices as $choice)
{
	// pre-check any existing choices
	$chk = in_array($choice,$_POST['vote']??[]) ? 'checked' : '';
?>
	<label><input type="checkbox" name="vote[]" value="<?=$choice?>" <?=$chk?>> <?=$choice?></label><br>
<?php
}
?>
<input type='submit'>
</form>

 

Link to comment
Share on other sites

9 hours ago, dodgeitorelse3 said:

Please show your form code

<form action="" method="post" name="election" id="election">

<?
	$db = mysqli_connect($db_hostname,$db_username,$db_password,"ptb_members") or die ("Cannot connect to MySQL");
	$result = mysqli_query($db,"SELECT * FROM NewBoard");
	while ($row = mysqli_fetch_array($result)) {
	extract($row); 

echo "<div class=\"flex-container\">
	<div>
	<input type=\"checkbox\" name=\"vote\" value=\"$lname\"> - $fname $lname
	<br><hr><br>
	<div style=\"text-align:center\">$country</div>
    </div>
    <div>
	<img src=\"./images/$photo\" alt=\"$fname $lname\" style=\"width:100%;max-width:200px;\">
	</div>
    <div class=\"valign\">
    <a href=\"$url\">Personal Profile & Statement</a>
    </div>
</div>   
 <br>"; 
	}
?>
<div style="text-align:center;">
<br>
<input type="submit" name="submit" value="Vote" class="formbutton">
</div>
</form>

 

Link to comment
Share on other sites

I thought I submitted my code before I headed out to work, but apparently I never hit the submit button. Because it is really irrelevant at this point, I did not mean to submit but I guess I did.

That being said, thank you all for some GREAT ADVICE.

Thank you mac_gyver AND Psycho, you have given me multiple solutions. Much appreciated :)

 

Link to comment
Share on other sites

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.