Store values of dynamically generated radio buttons in mysql - php

I am creating radio buttons dynamically. I need to write the posted data into a MySQL table. The radio buttons names will change as will the qty of buttons.
For example, if four radio buttons are created, the name of each is a variable, $proposed_id (a number), and the values are yes or no.
I wish to have have all of the posted data in one table field. I tried using an array ("props_yes[]") but of course each new one overwrites the previous button.
Thanks for any help.
$sql = "SELECT * FROM table WHERE ballot_name = '$ballot_id' ";
$sql_result = mysql_query($sql,$link);
while ($row = mysql_fetch_array($sql_result))
{
$proposed_id = $row['submission_id'];
echo '<input name="' . $proposed_id . '" id="' . $proposed_id . '_yes"type="radio" value="Yes" required > ';
echo '<label for="' . $proposed_id . '_yes">' . 'YES' . '</label> ';
echo '<input name="' . $proposed_id . '" id="' . $proposed_id . '_no" type="radio" value="No" required > ';
echo '<label for="' . $proposed_id . '_no">' . 'NO' . '</label><br>';
}

While I agree with #trincot that, in general, it is bad practice to store multiple, different kinds of values in a single DB field, there are times that it is called for or even necessary, as for example, when your database uses the EAV pattern as do some popular systems like Wordpress. If this is the primary data that is being stored in your database, you might want to consider a NoSQL database for this project.
That being said, here is how you might handle storing and retrieving your data. First, I would add some key word to the name field of your radio inputs, e.g. name="ballot_'.$proposed_id.'" so that you don't end up with a bunch of fields with numbers as names, and so that you have some way to filter the results on the server side. On the server side then you could do something like (assuming the form was submitted using POST):
// create an associative array of values from your radio buttons
$ballot_values = array();
foreach ($_POST as $index => $value) {
if (false !== strpos($index, 'ballot_')) {
$id = substr($index, 7); // get the numeric part of the name
$ballot_values[$id] = $value;
}
}
Once you do this, $ballot_values will contain an associative array of IDs and yes/no values. In order to save this in a single database field, you need to serialize the array, i.e.
$serialized_ballot_values = serialize($ballot_values);
This will store the array as a single string that you can then store in your DB field. When you retrieve the value from the database, you'll have to unserialize it before you can use it.
Again, if you can avoid doing this, I would. Unfortunately, though, we don't always have control over the structure of the DB so it could be that you have no choice.

Use an array with keys in your radio button names. PHP will interpret the submitted values into an array.
$sql = "SELECT * FROM table WHERE ballot_name = '$ballot_id' ";
$sql_result = mysql_query($sql,$link);
while ($row = mysql_fetch_array($sql_result))
{
$proposed_id = $row['submission_id'];
echo '<input name="props_yes[' . $proposed_id . ']" id="' . $proposed_id . '_yes"type="radio" value="Yes" required > ';
echo '<label for="' . $proposed_id . '_yes">' . 'YES' . '</label> ';
echo '<input name="props_yes[' . $proposed_id . ']" id="' . $proposed_id . '_no" type="radio" value="No" required > ';
echo '<label for="' . $proposed_id . '_no">' . 'NO' . '</label><br>';
}
After the post, the value of $_POST['props_yes'] will contain an array of chosen answers. The keys in the array will be from the $proposed_id

Related

Get value for checkbox in html/php from database(mysql)

I have data stored in database in varchar format like for eg: S,M,L,XL , I have checkboxes for these in my php page. Is it possible to retrieve these from database and show already checked boxes in php/html. (When there is just XL value , only XL checkbox should be checked in html/php page )
I have done this in my project and I do not recommend.
You can store an enum array of values in PHP and then use it to create the form. Selecting the data from database is not different than any other query. You can then compare the value from the database to the value in your array.
define('SIZES', ['S', 'M', 'L', 'XL']);
$value_from_db = 'L'; // Fetched from the database
echo '<form>';
foreach (SIZES as $size) {
if ($value_from_db == $size) {
echo '<label><input type="checkbox" value="' . $size . '" name="size" checked />' . $size . '</label>';
} else {
echo '<label><input type="checkbox" value="' . $size . '" name="size" />' . $size . '</label>';
}
}
A better option would be to store these values in a reference table in the database instead of in PHP. You can then enforce the referential integrity. Instead of looping on the array, you would loop on the values from the reference table.
One way of doing is :
- you retrieve the database values using SQL in PHP
- Dynamically create the checkbox HTML using the retrieved values

Modx: FormIT Select fields not persistent when values are loaded from MySQL table

I know that the formItIsSelected utility works perfectly well to keep the value of a Select field in a form when (for example) the form fails to validate for some reason. But has anybody tried to use this when a Select field populates from a table in MySQL? This is surely more useful than a Select field populated with static values..
I have a form in a modx site, hooked with formit and a select field in it retrieves dynamically values from a table in MySQL. When the form fails to validate this specific field loses the value the user has selected. My field (in the form) has the following setting:
<select id="Field245" name="typeOfRelationship" class="field select medium" tabindex="4">[[!getRelationshipOptions? &selected=`[[!+fi.typeOfRelationship]]`]]</select>
and the snippet and which works correctly simply does:
<?php if (!$modx->addPackage('contacts', MODX_CORE_PATH . 'components/contacts/model/')) {return 'Could not load xPDO model';}$current = $modx->getOption('selected', $scriptProperties, '');$output = [];$relationships= $modx->getCollection('RelationshipCodes');foreach ($relationships as $relationship) {$selected = $current == $relationship->get('codes') ? 'selected="selected' : '';$value=$relationship->get('descriptions');$output[] = '<option value="' . $relationship->get('descriptions') . '" ' . $selected . '>' . $relationship->get('descriptions') . '</option>';}return implode('', $output);
So far so good. But when I replace the $output[] line with:
$output[] = '<option value="' .$value . '" '. '[[!+fi.typeOfRelationship:FormItIsSelected=' ."'".$value. "'". $selected. ']]>' . $value . '</option>';
this fails! It doesn't error but it still allows the Select field to lose its setting when the form fails validation. Do you see a problem? Or maybe FormItIsSelected does not work in that context?
Many many thanks

PHP loop generated buttons - only last one works?

First time posting, and PHP is not my strongest area, so here goes...
My code below generates a list of buttons depending on how many values are found in my DB Table, then the second piece of code is supposed to trigger when the buttons are clicked. Everything is working except that the second piece of code only works for the last button generated. Any ideas?
<?php
$username = $_SESSION['sess_user'];
$con=mysql_connect('localhost','root','root') or die(mysql_error());
mysql_select_db('user_registration') or die("cannot select DB");
$loop = mysql_query("SELECT * FROM `vaults` WHERE username = '$username' ORDER BY vaultname asc") or die ('Error Getting User Data! <br />' .mysql_error());
$chk = mysql_num_rows($loop);
$myvalue = '';
while ($row = mysql_fetch_assoc($loop)) {
$myvalue = "{$row['vaultname']}";
echo '<form method="post"><input class="text-center" type="submit" name=' . $myvalue . ' value=' . $myvalue . ' id="vaultSelecter"></form>';
}
?>
<?php
if(isset($_POST[$myvalue])){
echo '<script type="text/javascript">window.onload = function() { document.getElementById("instructions").innerHTML = " HELLO WORLD! "; }</script>';}
?>
Thank you all for your replies, I appreciate it. I understand what everyone is saying, but the ID I reference in my getELementByID() is a separate DIV from the buttons, I want to change the content of the single DIV with the ID "instructions", when any of the buttons are clicked, but it only works for the last button created by the loop. Is that still due to the way I have my buttons ID'd?
For example say the above loop creates three buttons, I want each button to change the contents of the following DIV with "Hello Word".
<div id=instructions>
replace this text
</div>
I am guessing I have to store each of the $myvalues created by the loop into an array, so that each value can be assigned separately to each button, I just have no idea how to do that.
You're duplicating IDs in this line:
echo '<form method="post"><input class="text-center" type="submit" name=' . $myvalue . ' value=' . $myvalue . ' id="vaultSelecter"></form>';
and IDs must be unique. Try classes instead. Ex:
var elems = document.getElementsByClassName("text-center");
for (var i = 0; i < elems.length; i++) {
console.log('x')
elems[i].addEventListener('click', function () {
alert('hello');
}, false);
}
You're assigning multiple inputs to the same id, assign them to a class instead since id's have to be unique.
You're also making a form for every button, which seems kind of pointless to me, try this instead:
echo '<form method="post">';
while ($row = mysql_fetch_assoc($loop)) {
$myvalue = "{$row['vaultname']}";
echo '<input class="text-center vaultSelecter" type="submit" name=' . $myvalue . ' value=' . $myvalue . '>';
}
echo '</form>';
The id called vaultSelector is now a class, so can be accessed via getElementByClassName()
Instead of this:
name=' . $myvalue . ' value=' . $myvalue . ' id="vaultSelecter"
Maybe try
name="' . $myvalue . '" value=' . $myvalue . ' id="' . $myvalue . '"
In my opinion it is best to uniquely identify any elements that will be used as a programming element.
Just another piece of unsoliciated opinion. If you can put everything in one form it may make things easier. So when the button submits set a hidden field and continue with the form submit.

How can $_POST pass input variables to MySQL query as integers, not 1?

I have a table of numbers where the user should be able to edit the values and have the database updated on submit.
So far, my faulty code is updating every field with the value 1 on submit, regardless of what has been inputted.
Code on submit:
//If the confirm button has been hit:
if (isset($_POST['submit'])) {
//Create the foreach loop
foreach($_POST['classtoupdate'] as $classes){
//Grab the POST data and turn it into integers
$class_id = (int)$classes;
$totalspcs = (int)$_POST['allspaces'];
$totalbkgs = (int)$_POST['allbookings'];
$newbies = (int)$_POST['noobs'];
//Change the booking numbers:
$newdeets = "UPDATE classes SET total_spaces = '$totalspcs', total_bookings = '$totalbkgs', free_spaces = ('$totalspcs' - '$totalbkgs'), newbies = '$newbies' WHERE class_id = '$class_id')";
echo $newdeets;
mysqli_query($dbc, $newdeets);
}
mysqli_close($dbc);
echo 'All good, yay! Go look';
}
Form:
//create the form
echo '<form method="post" action="' . $_SERVER['PHP_SELF'] . '" >';
echo '<tr><td>' . $class . '</td>';
echo'<td>' . $new_date . '</td>';
echo '<td>' . $new_time . '</td>';
echo '<td><input type="text" maxlength="2" class="input-mini" name="noobs[]" id="noobs[]" value="' . $newbies . '">';
echo '<td><input type="text" maxlength="2" class="input-mini" name="allspaces[]" id="allspaces[]" value="' . $totalspaces . '">';
echo '<td><input type="text" maxlength="2" class="input-mini" name="allbookings[]" id="allbookings[]" value="' . $bookings . '"
>';
echo '<td>' . $freespaces . '</td>';
echo' <input type="hidden" name="classtoupdate[]" id="classtoupdate[]" value="' . $class . '" />';
}
echo'</table>';
// Make booking button
echo '<input type="submit" name="submit" class="btn btn-large btn-primary pull-right" value="Update">';
echo '</form>';
The echoed query results after inputting random values (not 1) in the form:
UPDATE classes SET total_spaces = '1', total_bookings = '1', free_spaces = ('1' - '1'), newbies = '1' WHERE class_id = '26')
UPDATE classes SET total_spaces = '1', total_bookings = '1', free_spaces = ('1' - '1'), newbies = '1' WHERE class_id = '16')
..and so on for each table row. I can't find the problem replicated after extensive searching on SO and in the manuals.
I've tried intval(), serialize and array_map on the POST results (probably incorrectly); I've tried different foreach loops to translate them into integers, still no joy.
Any advice?
try this:
foreach($_POST['classtoupdate'] as $index => $classes){
and
$totalspcs = (int)$_POST['allspaces'][$index];
$totalbkgs = (int)$_POST['allbookings'][$index];
$newbies = (int)$_POST['noobs'][$index];
note the $index in each line.
$i=0;
//Create the foreach loop
foreach($_POST['classtoupdate'][$i] as $classes){
//Grab the POST data and turn it into integers
$class_id = (int)$classes;
$totalspcs = (int)$_POST['allspaces'][$i];
$totalbkgs = (int)$_POST['allbookings'][$i];
$newbies = (int)$_POST['noobs'][$i];
//Change the booking numbers:
$newdeets = "UPDATE classes SET total_spaces = '$totalspcs', total_bookings = '$totalbkgs', free_spaces = ('$totalspcs' - '$totalbkgs'), newbies = '$newbies' WHERE class_id = '$class_id')";
echo $newdeets;
mysqli_query($dbc, $newdeets);
$i++;
}
your POST variables are arrays (e.g. allspaces[])
so, this assignment is always giving you 1 as a result, because you're trying to cast an array to integer.
$totalspcs = (int)$_POST['allspaces'];
you should cycle your array and use the data in a different way.
If you don't need an array, get rid of the square brackets in the input name.
The problem is with the way you have named your input fields. <input type="text" maxlength="2" class="input-mini" name="noobs[]"> The [] means that the data will be posted back to the server as an array, and you are type casting an array into an integer, which is why everywhere you are getting 1 as value. Lose the [], eg. <input type="text" maxlength="2" class="input-mini" name="noobs"> should fix the problem.
I made an example you should be able to use to solve your problem.
<?php
$foo = array('1','2','3');
$bar = array('4','5','6');
// Simulates the $_POST variable
$baz = array('foo'=>$foo, 'bar'=>$bar);
// You should ensure that all entries have an equal length before iterating through!
if(count($baz['foo']) === count($baz['bar'])){
foreach($baz['foo'] as $key=>$value){
$x = (int)$value;
$y = (int)$bar[$key];
var_dump($x, $y);
}
}
?>
The problem that you're having is that, even though you're looping through $_POST['classtoupdate'], you are still using $_POST['allbookings'] and other fields which are still arrays.
Converting an array to an integer value will always return 1 if the array is not empty. So you'll have to extract the values from them.

Display checkbox values in HTML after select, submit and email results from process.php

I have a checklist that's broken down into days, stage, timeShow, and bandName. I am displaying the options from a database with this script and I'm trying to display the results (and eventually email them) to the user on the 'process' page. How do I carry over the $result_x to the following page?
Here's an example of one of the 'blocks' for Saturday, Stage 1 and the value of the selection is the 'ID' of the row.
UPDATE- Part one is solved. Now looking to get the results sent to an email address input by the user.
FORM SOLUTION- 'Selection.php'
$sql_Sat1 = "SELECT * FROM bandSched WHERE day='saturday' AND stage='stage 1'";
mysql_query($sql_Sat1);
$result_Sat1 = mysql_query($sql_Sat1);
while($row = mysql_fetch_array($result_Sat1))
{
echo "<ul><li>";
echo'<input type="checkbox" name="id[]" value="'.$row['id'].' " id="bandSched_' . $row['id'] . '" />';
echo '<label for="bandSched_' . $row['id'] . '">' . $row['timeShow']." ".$row['bandName'] . '</label>';
echo "</li></ul>";
}
SOLUTION- 'process.php'
if ( ! empty($_POST['id']))
{ foreach($_POST['id'] as $key => $id) { $_POST['id'][$key] = mysql_real_escape_string($_POST['id'][$key]); }
$in = implode(', ', $_POST['id']);
$sql_Sat2 = "SELECT * FROM bandSched WHERE id IN ($in) ORDER BY FIELD(id, $in)";
$result = mysql_query($sql_Sat2) or die('MySQL Error ' . mysql_errno() . ': ' . mysql_error());
}
if ( ! isset($result))
{
echo 'You did not select anything';
}
else
{
while ($row=mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>". $row['timeShow'] ."</td><td>" . $row['bandName'] . "</td>";
echo "</tr>";
}
}
Unless you have the attribute checked="checked" in your <input type="checkbox" />, the value will not be sent with the form data.
Try this:
echo '<input type="checkbox" value="' . $row['id'] .'"name="selected" checked="checked" />';
Does this solve the problem?
Carrying data from page to page can either be done with Sessions, Cookies, or posting hidden form elements containing the data.
Sessions provide you the data, but you still need to make a valid query. The only thing that sessions do are store data on the server. They do not keep any of the program execution, variables, etc.
Your error message is telling you that mysql_fetch_array was not supplied a MYSQL result resource (and it wasn't you supplied it an integer of the id value). The query will not be remembered across the session.
Also, mysql_* is deprecated, use PDO or mysqli.

Categories