multiple post values in for each php - php

So I am working with some checkboxes that are populated from a db table. Which looks like this.
<form action="" method="post">
<?php
foreach ($chores as $retrieved_search){
?>
<tr>
<td>
<?php echo "<input type='checkbox' id=".$retrieved_search->id." value=".$retrieved_search->image." name='chores[]'>$retrieved_search->name";?>
<?php echo "<input type='text' value='$retrieved_search->name' id='optionName' name='optionName[]' />"?>
</td>
</tr>
<?php
}
?>
</form>
I am trying to figure out a way that I can get that value from the checkbox which I am currently doing and works fine. The value from the checkbox is an image URL.
I also need to get the name associated with the checkbox so I added another input field that is populating the name of the checkbox which I will then hide.
So this is my php statement that is getting the post value from the checkbox but how can I also get the value from the input field for the same insert statement?
<?php
if(isset($_POST['saveOptions'])) {
global $wpdb;
$table_name = $wpdb->prefix . "chartUsersOptions";
$user_ID = get_current_user_id();
$typeChore = "chore";
$typeBehavior = "behavior";
if(isset($_POST['chores'])){
foreach ($_POST['chores'] as $chores) {
$wpdb->insert( $table_name, array(
'userId' => $user_ID,
'optionImage' => $chores,
'type' => $typeChore,
));
}
}
$msg = "Saved now redirect to 3rd step";
echo $msg;
}
else{
.............
}
?>
EDIT:
Based on a suggestion This worked.
<?php
foreach ($chores as $retrieved_search){
echo "<input type='checkbox' value='{$retrieved_search->image}' name='chores[{$retrieved_search->id}]'>{$retrieved_search->name}";
echo "<input type='text' value='{$retrieved_search->name}' name='optionName[{$retrieved_search->id}]'>"
}
?>
And This
if(isset($_POST['chores'])){
foreach ($_POST['chores'] as $chores_key => $chores) {
$text_input_value = $_POST['optionName'][$chores_key];
$wpdb->insert( $table_name, array(
'userId' => $user_ID,
'optionImage' => $chores,
'optionName' => $text_input_value,
'type' => $typeChore,
));
}
}
But optionName is still inserting blank.

I'm not sure what the exact problem is, but my guess is that your checkboxes don't match your input boxes. That is because unchecked checkboxes do not get sent to the server, so you probably end up with an checkboxes array that is smaller than the input boxes array.
You should change your html so that a checkbox-array-key always matches an input-array-key, so something like:
echo "<input type='checkbox' value='{$retrieved_search->image}' name='chores[{$retrieved_search->id}]'>{$retrieved_search->name}";
echo "<input type='text' value='{$retrieved_search->name}' name='optionName[{$retrieved_search->id}]'>"
Also note that ID's need to be unique so I removed them but that is probably not related to your problem.
Edit: To get the value of the text box after making the above changed, you can do:
if (isset($_POST['chores'])) {
foreach ($_POST['chores'] as $chores_key => $chores) {
$text_input_value = $_POST['optionName'][$chores_key];
// and the rest of your code

Instead of
foreach ($_POST['chores'] as $chores) {
you want
foreach ($_POST['chores'] as $id=>$chores) {
Then you can access
optionName[$id]
in your loop.

Related

Comparing only the selected value in loop to avoid error message

I am trying to build a basic quiz system.The following code shows how user choose the answer using radio butto and the getresult.php compares the radio input value with answer column. In my database there is a question, opt1, opt2, opt3, opt4, and answer columns.
<form method="POST" action="getresult.php">
<label>Enter Your Name:</label><br>
<input type="text" name="name"><br><br>
<?php
$db = new mysqli("localhost", "root", "","learndb");
$stmt=$db->prepare("SELECT * FROM quiz");
$stmt->execute();
$result=$stmt->get_result();
echo "<form method='POST' action='getresult.php'>";
while($myrow = $result->fetch_assoc())
{
echo $myrow['id'];
echo ".";
echo $myrow['question'];
echo "<br>";
echo "<input type='radio' name='mycheck[".$myrow['id']."]' value=".$myrow['opt1'].">";
echo $myrow['opt1'];
echo "<br>";
echo "<input type='radio' name='mycheck[".$myrow['id']."]' value=".$myrow['opt2'].">";
echo $myrow['opt2'];
echo "<br>";
echo "<input type='radio' name='mycheck[".$myrow['id']."]' value=".$myrow['opt3'].">";
echo $myrow['opt3'];
echo "<br>";
echo "<input type='radio' name='mycheck[".$myrow['id']."]' value=".$myrow['opt4'].">";
echo $myrow['opt4'];
echo "<br><br>";
}?>
<input type="submit" name="submit" value="Get Results" class="btn btn-primary">
// getresult.php
<?php
extract($_POST);
$db = new mysqli("localhost", "root", "","learndb");
$stmt=$db->prepare("SELECT * FROM quiz");
$stmt->execute();
$result=$stmt->get_result();
$submit=isset($_POST['submit']);
$count=0;
if($submit)
{
while($myrow = $result->fetch_assoc())
{
if($mycheck[$myrow['id']]==$myrow['answer'])
{
$count=$count+1;
}
}
echo "Hello ";
echo $_POST['name'];
echo "<br>";
echo "You scored ";
echo "$count";
}
Everything is correct, but if I do not select a radio button from a question, i.e if I leave the question it displays undefined offset error which is obvious but how can I not display that. OR how can I compare only chosen options?
You should try array_key_exists() like this:
if(array_key_exists($myrow['id'], $mycheck)
&& array_key_exists('answer', $myrow)
&& $mycheck[$myrow['id']]==$myrow['answer'])
{
$count=$count+1;
}
Or better yet, request your answers from database based on validated rows.
When the form is submitted, the chosen values are passed as (for example):
mycheck[1]=2
mycheck[2]=3
mycheck[3]=1
mycheck[4]=2
...etc. Now if you leave one question unanswered, let's say question 2, then no value will be submitted to the server for that question, so the submitted values could be something like this:
mycheck[1]=2
mycheck[3]=1
mycheck[4]=2
When PHP stores this in $_POST[], it will be an associative array:
$_POST['mycheck'] === array(
'1' => 2,
'3' => 1,
'4' => 2
)
With extract($_POST) you get the following value for $mycheck:
$mycheck === array(
'1' => 2,
'3' => 1,
'4' => 2
)
Now the following loop in your code will still go through all questions:
while($myrow = $result->fetch_assoc())
{
if($mycheck[$myrow['id']]==$myrow['answer'])
{
$count=$count+1;
}
}
But (in the example) the check for question 2 will fail, because $myrow['id'] will equal 2, while $mycheck[2] does not exist. This produces the undefined offset error.
As an unanswered question obviously should not increase the count, you could solve this issue as follows: first test if the question was answered (does $mycheck have an entry for it?), and only if that is the case, retrieve the answer from that entry:
while($myrow = $result->fetch_assoc())
{
$id = myrow['id'];
if(array_key_exists($id, $mycheck) && $mycheck[$id]==$myrow['answer'])
{
$count=$count+1;
}
}
For the above extra test you can use array_key_exists, or isset.
A bit rusted on PHP, but ...
Have you tried using the isset() function? Or changing the error reporting level appropriately?
http://php.net/manual/pt_BR/function.error-reporting.php
Why don't you create a new radio button "Don't know " which would be initially checked
<input type="radio" name="" checked>
So by default that button will be checked.

How can i delete from the table a value from a foreach loop?

I created a table in HTML, and I'm inserting all the information from a specific database table, into this HTML table using a foreach loop.
I created a button called delete, to delete a specific row from the database, but I'm having some problems because I don't know how I can delete the table information using a foreach loop, because I always use a while statement.
I'm doing a kind of MVC structure, but with my own rules, so I got the model and the view, I'm calling all the functions at view.
And I'm doing something like this on view:
function fname($array) {
foreach($array as $key) {
echo $key['row1'];
echo "<input type='submit' value='delete'";
}
}
And I made my function on model:
function function() {
connect();
$show = ("SELECT * FROM mytable");
$array = db_array($show, 'v');
fname($array);
}
Can you guys help me with an example? Thanks.
Create a form inside the loop for each row i.e. if it prints out 10 rows it means 10 different forms. While submitting form (clicking delete), send the row id as hidden parameter to the controller (in action) while in turns send it to model. Model has the delete query which gets execute and the row gets deleted.
View -
foreach($array as $key)
{
$row_id = $key['row_id'];
echo "<form action='/deleterow' method='POST'>"
echo $key['row1'];
echo "<input type='submit' value='delete'>";
echo "<input type='hidden' name='id' value=$row_id>";
echo "</form>";
}
Controller -
function deleterow($id)
{
$this->model_name->delete($id);
}
Model -
function delete($id)
{
$sql = "DELETE FROM table_name WHERE id=$id";
$exe = mysql_query($sql) or die(mysql_error());
}
I would try this
function fname($array){
foreach($array as $key=>$val){
echo $val['FIELD'];
echo '<input name="Z" type="hidden" value="'.$key.'" />';
echo '<input type="submit" value="Delete"/>';
}
}
I am assuming you are going to make a page where someone can delete something?
You need to echo out the recode name? (this depends on what you are pulling out of the table and fields involved)
The when the delete button is pressed you can act upon hidden field Z

PHP Form from Array Select Value Edit/Save

I'm using an array to output a form for product entry.
$labels = array(
"category" => "Model",
"model_number" => "Model No.",
"description" => "Description");
The categories are populated as select/option set, which is easy when adding a new product. The issue comes when I need to edit the product. I would like to query the category table to return all the available categories to populate the select/option set. At the same time, I need to query the products table so that I can provide their saved Model Number and Description.
The following is my code from the add form to give you an idea of how I'm structuring this.
foreach($labels as $field => $label) {
if($field == "category") {
echo "<label>$label:</label>";
echo "<select name=\"$field\">";
while($row=mysqli_fetch_assoc($result)) {
extract($row);
echo "<option value=\"$category\">$category</option>";
}
echo "</select>";
echo "<br />";
}
else {
echo "<label>$label:</label>";
echo "<input type=\"text\" name=\"$field\" />";
echo "<br />";
}
Thanks for the help. I'm sure it's simple, but my brain isn't quite providing me with the solution at the moment.
Having $labels array is a bad idea.
Get all your data first. Select your product data into array. Select your categories into array.
Show the form, as any other HTML you create with PHP
<label>Model:</label>
<select name="category">
<? foreach($cats as $category): ?>
<option<? if ($category == $row['category'])?> selected?>><?=$category?></option>
<? endforeach ?>
</select>
<br />
<label>Model No.:</label>
<input type="text" name="model_number" value="<?=$row['model_number']?>"/>
<br />
and so on
don't forget to htmlspecialchars() your values before placing them into value attribute
you can query the product table like this:
$sql = "SELECT * FROM products WHERE product_id = $product_id";
$q = mysql_query( $sql );
$row = mysql_fetch_assoc( $q );
$model_number = $row['model_number'];
$description = $row['description'];
$category = $row['category'];

Dynamically creating checkboxes

i am new to php.I want to dynamically create check boxes upon the result fetched from MySQL.If i have 10 records in employee Table so it must create 10 check boxes with employee name as value.I had seen several tutorials to make array of check boxes etc but could not fix the problem.Please anyone there to help!!!
Try this out:
<?php
//Create the query
$sql = "SELECT `name` FROM Employees";
//Run the query
$query_resource = mysql_query($sql);
//Iterate over the results that you've gotten from the database (hopefully MySQL)
while( $employee = mysql_fetch_assoc($query_resource) ):
?>
<span><?php echo $employee['name']; ?></span>
<input type="checkbox" name="employees[]" value="<?php echo $employee['name']; ?> /><br />
<?php endwhile; ?>
The example you see above relies on two things to actually function properly:
You're using MySQL
Your SQL-query must retrieve the employees' names (so that you can use them in the loop
MySQL is just a source of data. The same process would apply to making a checkbox list from ANY data source (array, file contents, database, etc...). A skeleton framework for the process would be:
$sql = "select idfield, namefield FROM sometable ...";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo <<<EOL
<input type="checkbox" name="name[]" value="{$row['namefield']}" /> {$row['namefield']}<br />
EOL;
}
Note that I've use the "name field"as you specified. But consider the case where you've got 2 or more John Smith's working for you - it is far more reliable to use the employee's ID number (whatever it may be in your database) than their name.
Lets say the result you fetched is in the $result array.
The array has 10 sub-arrays - each one looking like this:
[0] => array
['name'] => 'ZainShah'
[1] => array
['name'] => 'Stack'
The easiest way to do this is:
foreach ( $result as $key => $employee ) {
echo '<label for="employee' . $key . '">' . $employee['name'] . '</label>'
echo '<input type="checkbox" name="employee[]" id="employee' . $key . '" value="' . $employee['name'] . '" />';
}
I have made it easy to create checkboxes as well as radio buttons in any php form. Only thing is I am using Codeigniter MVC framework.
Here is the function definition that you can insert in your common-model or any helper file.
function createOptions($fieldName, $labelsArray=array(), $selectedOption, $fieldType,$valuesArray = array()) {
$returnString = '';
if(count($valuesArray)!=count($labelsArray))
$valuesArray=$lebelsArray;
if ($fieldType === 'checkbox') {
for ($i=0;$i<count($labelsArray);$i++) {
$returnString.='&nbsp&nbsp&nbsp<input type="checkbox" name=' . $fieldName.' value='.$valuesArray[$i].' id='.$valuesArray[$i];
if(in_array($valuesArray[$i], $selectedOption)){
$returnString.=' checked="checked" ';
}
$returnString.=' />&nbsp&nbsp<label>'.$labelsArray[$i].'</label>';
}
}
if ($fieldType === 'radio') {
for ($i=0;$i<count($labelsArray);$i++) {
$returnString.='&nbsp&nbsp<input type="radio" name=' . $fieldName.' value='.$valuesArray[$i].' id='.$valuesArray[$i];
if($valuesArray[$i]== $selectedOption)
$returnString.=' checked="checked" ';
$returnString.=' /><label>'.$labelsArray[$i].'</label>';
}
}
return $returnString;
}
And, you have to call this function in view file as,
<?php
echo $this->common_model->createOptions('userHobbies[]', $hobbyOptions, $userHobbies, 'checkbox'); ?>
First parameter is name of checkbox field or radio field, which is always gonna be same for all options for both cases. Second is labels array, Third is selected options which will show those options as checked while loading the form. Fourth is type of field that will be a string as 'checkbox' or 'radio'. Fifth will be values array, which, if present, will contain values for labels in the same order as that of labels. If its absent, labels array will be teated as values array
This is fairly straightforward. I'll assume that your MySQL result data is in an array called $employees, containing at least 2 elements: id and name. You mention that the "value" of the checkbox needs to be the name, but I'll assume that's what you want displayed in the HTML next to the checkbox. It would be better to have the "value" be the id of the database record for each employee (since employees might have the same name). Creating the HTML for the checkboxes is simply a matter of iterating through them with a foreach() loop, and creating a php variable to hold the HTML.
So, assuming your $employees array looks something like this:
[0] =>
'id' => '1'
'name' => 'Sam Jones'
[1] =>
'id' => '2'
'name' => 'Tom Smith'
[2] =>
'id' => '3'
'name' => 'Sarah Conners'
Just need to run through the array and create the output:
// init the var to hold the HTML
$output = '';
// cook the HTML
foreach ($employees AS $k=>$v) {
$output .= "<input type='checkbox' name='employee_array[]' value='" . $v['id'] . "'> " . $v['name'] . "<br />";
}
In your HTML form, just echo the $output variable. Notice that the ".=" operand is used to append to the $output variable I created. And the "name" of the form field ends in "[]". This will create an array named "employee_array" that gets passed back to PHP when the form is submitted. Each item that is checked becomes an element of that array, with its value being the ID of the employee record.
Hope that makes sense...
set echo in for loop you will always be able to set the loop variablenow simply echo/print the code

Keep selections in php generated form after submit (POST)

I'm currently using php to populate a form with selections from a database. The user chooses options in a select style form and submits this, which updates a summary of the selections below the form before a second submit button is used to complete the interaction.
My issue is that every time a user uses the first submit, the selections that were there previously do not stick. They have to go through the whole form again.
Is there anyway to keep these selections present without resorting to php if statements? There are a ton of options so it would be a pain to use php for each one. Also, form is being submitted via POST.
Sample from form:
<?php
// GRAB DATA
$result = mysql_query("SELECT * FROM special2 WHERE cat = 'COLOR' ORDER BY cat")
or die(mysql_error());
echo "<div id='color'><select id='color' name='product_color'>";
while($row = mysql_fetch_array( $result )) {
$name= $row["name"];
$cat= $row["cat"];
$price= $row["price"];
echo "<option value='";echo $name;echo"'>";echo $name;echo" ($$price)</option>";}
echo "</select>";
echo "<input type='hidden' name='amount_color' value='";echo $price;echo"'></div>";
?>
I tried using this js snippet to repopulate the selections, but it does not seem to work properly...
<script type="text/javascript">document.getElementById('color').value = "<?php echo $_GET['proudct_cpu'];?>";</script>
This does not seem to work. Any suggestions other than php if statements?
Thanks!
edit: This is basically the form set up I'm using, though I've shortened it significantly because the actual implementation is quite long.
// Make a MySQL Connection
<?php mysql_connect("localhost", "kp_dbl", "mastermaster") or die(mysql_error());
mysql_select_db("kp_db") or die(mysql_error());
?>
<br />
<form action="build22.php" method="post">
<input type="hidden" name="data" value="1" />
<br />
<br />
<?php
// GRAB DATA
$result = mysql_query("SELECT * FROM special2 WHERE cat = 'color' ORDER BY cat")
or die(mysql_error());
echo "<div id='color'><select id='color' name='product_color'>";
while($row = mysql_fetch_array( $result )) {
$name= $row["name"];
$cat= $row["cat"];
$price= $row["price"];
echo "<option value='";echo $name;echo"'>";echo $name;echo" ($$price)</option>";}
echo "</select>";
echo "<input type='hidden' name='amount_color' value='";echo $price;echo"'></div>";
?>
<input type="submit" value="Update Configuration">
</form>
The selections from the form above get echoed after submission to provide the user with an update as such:
<div id="config" style="background-color:#FFF; font-size:12px; line-height:22px;">
<h1>Current Configuration:</h1>
<?php echo "<strong>Color:</strong>&nbsp&nbsp&nbsp&nbsp";echo $_POST['product_color']; ?>
</div>
I assume you're storing the user's selections in a separate table. If that's the case, you'll need to add some logic to determine if you should display the form values or what's already been stored.
<?php
// form was not submitted and a config id was passed to the page
if (true === empty($_POST) && true === isset($_GET['config_id']))
{
// make sure to properly sanitize the user-input!
$rs = mysql_query("select * from saved_configuration where config_id={$_GET['config_id']}"); // make sure to properly sanitize the user-input!
$_POST = mysql_fetch_array($rs,MYSQL_ASSOC); // assuming a single row for simplicity. Storing in _POST for easy display later
}
?>
<div id="config" style="background-color:#FFF; font-size:12px; line-height:22px;">
<h1>Current Configuration:</h1>
<?php echo "<strong>Color:</strong>&nbsp&nbsp&nbsp&nbsp";echo $_POST['product_color']; ?>
</div>
So after storing the user's selections in the database, you can redirect them to the page with the new config_id in the URL to load the saved values. If you're not storing the selected values in a table, you can do something similar with cookies/sessions.
echo the variables into the value tag of the form elements. If you post all your code I'm sure I can help you.
UPDATE
ah, so they are dropdown lists that you need to remember what was selected? Apologies, I read your post in a rush yesterday and thought it was a form with text inputs.
I just did a similar thing myself but without trying your code let me see if I can help.
Basically what you need to do is set one value in the dropdown to selected="selected"
When I had to do this I had my dropdown values in an array like so:
$options = array( "stack", "overflow", "some", "random", "words");
// then you will take your GET variable:
$key = array_search($_GET['variablename'], $options);
// so this is saying find the index in the array of the value I just told you
// then you can set the value of the dropdown to this index of the array:
$selectedoption = $options[$key];
This is where it might be confusing as my code is different so if you want to use it you will probably need to restructure a bit
I have a doSelect function to which I pass the following parameters:
// what we are passing is: name of select, size, the array of values to use and the
// value we want to use as the default selected value
doSelect("select_name", 1, $options, $selectedoption, "");
// these are the two functions I have:
// this one just processes each value in the array as a select option which is either
// the selected value or just a 'normal' select value
FUNCTION doOptions($options, $selected)
{
foreach ($options as $option)
{
if ($option == $selected)
echo ("<option title=\"$title\" id=\"$value\" selected>$option</option>\n");
else
echo ("<option title=\"$title\" id=\"$value\">$option</option>\n");
}
}
// this is the function that controls everything - it takes your parameters and calls
// the above function
FUNCTION doSelect($name, $size, $options, $selected, $extra)
{
echo("<select class=\"\" id=\"$name\" name=\"$name\" size=\"$size\" $extra>\n");
doOptions($options, $selected);
echo("</select>\n");
}
I know that's a lot of new code that's been threw at you but if you can get your select values from the db into the array then everything else should fall nicely into place.
The only thing I would add, is at the start where we call doSelect, I would put that in an if statement because you don't want to set something as selected which hasn't been set:
if (isset($_GET['variable']))
{
$key = array_search($_GET['variablename'], $options);
$selectedoption = $options[$key];
doSelect("select_name", 1, $options, $selectedoption, "");
}
else
{
doSelect("select_name", 1, $options, "", "");
}
I hope that helps!

Categories