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

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

Related

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

Store values of dynamically generated radio buttons in mysql

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

How to generate a state/province dropdown that selects the value in the database

So I have several places for country and state/province dropdowns. What I'd like to do is have a function for each of these and when I run my while loop on customer data from mysql I want to select the right by default from the data in the database.
Reason is right now the dropdowns default to the HTML selected one so if users don't change it to theirs again when they edit their account they re-save their info with the wrong state/country.
I'd also like to use this in several places so I want a big array of countries and states/provinces that loop.
Just looking for a hand or be pointed to where this has been done in a function already.
Thank you kindly.
$states - query with all states, $user_state - current user's state. So your user's choice will be selected by default.
<?php
echo '<select name="state">';
while ($state = mysql_fetch_assoc($states))
{
echo '<option value="' . $state['state'] . '"';
if ($user_state == $state['state'])
{
echo ' selected';
}
echo '>' . $state . '</option>';
}
echo '</select>';

PHP MySQL Drop Down Box Populate Selected Value

I have read tutorials about how to populate an entire Drop down list with MySQL, but the problem I am running into is that I only want to grab the one from the database and have that be the selected one. So I would have like a drop down with three items (Item1, Item2, Item3) in the database its stored in a column called itemschoice which has a value of 'Item2'. How do I go about getting item2 to be selected when I load the drop down box?
In your <option> element add the selected attribute for the value that is in itemschoice.
Crude example using a made up function to get the choice:
$choice = get_items_choice();
$results = mysqli_query($sql);
echo '<select name="whatever">';
while($row = mysqli_fetch_array($results)) {
if ($row['choice'] === $choice) {
echo '<option value="' . $choice . '" selected="selected" />';
} else {
echo '<option value="' . $choice . '" />';
}
}
echo '</select>';
This is just an example, don't copy & paste this without adding some kind of error verification!

Loop through form input array

I have a dynamic output form where the text input fields have the same name. I need to loop through
the text inputs and insert multiple rows into the database for each text field input.
$sql="INSERT INTO orderitems (orderNum,productNum,quant)
VALUES
('$num1','$_POST[pNum]','$_POST[quant]')";
<input type="text" name="pNum" value="<?php echo $t1; ?>"> //may have several with same name
If you want to submit your form with multiple inputs with the same name, you should add [] to the name. Then you can use it on PHP-side as every array (i.e. looping with foreach)
<input type="text" name="pNum[]" value="<?php echo addslashes($t1); ?>">
(by the way, remember always about quoting)
and on PHP side:
foreach($_POST['pNum'] as $value)
{
// remember about quoting here, too
}
Soooo.... loop through them and insert multiple rows?
for ($i = 0; $i < count($_POST['pNum']); $i++) {
$sql = 'INSERT INTO orderitems (orderNum, productNum, quant) VALUES ('
. "'" . mysql_real_escape_string($num1) . "', "
. "'" . mysql_real_escape_string($_POST['pNum'][$i]) . "', "
. "'" . mysql_real_escape_string($_POST['quant'][$i]) . "'"
. ')';
}
Note the use of mysql_real_escape_string. Never, NEVER, NEVER inject values from $_POST or $_GET or $_COOKIE or any other value your user has supplied directly into a SQL statement. Besides the potential to break if the value contains a ', this can also be used maliciously to inject SQL that alters (or erases) your database.
You can insert many rows with an INSERT request, you have just to create it with PHP
http://dev.mysql.com/doc/refman/5.0/en/insert.html

Categories