how to retrieve checked values in php - php

I am a newbie in php. I have a form with multiple checkbox values. I wanna retrieve the checked values and diplay these values on other php form.
Below is the code which works perfectly fine if we add the checkboxes without while loop.
But when added through while loop I am not able to fetch the selected items.
xyzhtml.php(html form)
<?PHP
require ("DBConnect.php");
$selectQuery =mysql_query( "SELECT * FROM fruits where approved = 0");
while($row = mysql_fetch_array($selectQuery))
{
$fruit_name = $row['fruit_name'];
echo "<input type=\"checkbox\" name=\"things[]\" value=\"$fruit_name\">";
echo "<br>";
}
?>
On click of submit I call other php clled "xyz.php".
Below is the code used in it.
<?php
$checkBox = $_POST['things'];
echo $checkBox[0];
for($i=0; $i<sizeof($checkBox); $i++){
echo($checkBox[$i]);
}
?>
Please help.
Thanks in advance.

two things to check:
are you getting right values from the MySQL SELECT statement (check your HTML for empty checkboxes values and check your MySQL database for fruits that have approved field set to 0 to see if there are any)
when you don't tick a checkbox and submit the form, unticked checkboxes' values do not get submitted - have you thought about that?

Use foreach to record $_POST['things']
if (!empty($_POST['things'])) {
foreach ($_POST['things'] as $value) {
echo "the value are: ".$value;
}
}
Note: teh $_POST['things'] not $_POST['things[]']

I think your code should work, but it won't display anything if no checkboxes are selected.
I would however remove the explicit echo $checkbox[0] (unless this is for testing purposes).
Try a print_r($checkbox) to see what's actually in that array.

Related

Trying to copy data to a table with checkboxes, a form, and php

My webpage is pulling data from two tables - applications and archiveapps - and displays them using the following:
$sql = "SELECT * FROM applications";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Lots of info, including some html thrown in for style."
I want users to be able to click a checkbox listed next to each row and then hit an "Archive Selections" button that then moves all the selected entries from the applications table to the archiveapps one.
So far I've tried a form with it's code half in the echo above (so that a checkbox would go by each listed row from the $sql query) with the submit button outside (so that there would only be one "Archive Selections" button) but I'm sure this isn't proper syntax.
To actually move the data, I had this for the checkbox:
<form method='post' action=''><input type='checkbox' name='archname' value=".$row["charname"].">
(The above was inside an echo statement, so I assume it was able to pull the $row["charname"] no problem, but am unsure how to verify that.)
A little further down the page is the submit button and </form>.
And then I've got the function I want it to run when the submit button is clicked, to check if boxes have been selected and copy them into the archiveapps table. I'm sure there's something I'm missing here, probably in referencing what exactly is selected, and then copying that row's data to the other table... but honestly I just don't know enough about php to know what I'm missing.
if(!empty($_POST['archname'])) {
foreach($_POST['archname'] as $check) {
function archiveapp() {
$sqli="INSERT INTO archiveapps SELECT * FROM applications";
if ($conn->query($sqli) === TRUE) {
echo "<i>Archived</i>";
} else {
echo "Error: " . $sqli . "<br>" . $conn->error;
}}}}
Most of this has just been gathered from google searches and kind of mushed together, so I'm sure there are a lot of things done wrong. Any pointers or advice would be greatly appreciated!
Oh and my end goal is to copy the data to the archiveapps table and then delete it from the applications table, but for now I've just been focusing on the copying part, since I assume deleting a row will be fairly simple? Either way it's not the priority for this question.
Thanks in advance for any help!
Use a tool like FireBug to see what you are actually posting to server. You have multiple checkboxes with the same name, so you are sending only 1 value (the last checked, I think).
You need to send all of them, so use brackets after the name:
<!-- this is just an example -->
<input type="checkbox" name="archname[]" value="1">
<input type="checkbox" name="archname[]" value="2" checked>
<input type="checkbox" name="archname[]" value="3" checked>
Then on PHP, inside $_POST['archname'] you will get this:
Array(2, 3)
After this, you can do a foreach(...) loop like you are already doing, inserting only the ID you get from the $_POST variable:
foreach($_POST['archname'] as $id){
$sqli = "INSERT INTO archiveapps (id) VALUES (".(int)$id.")";
}

Check Multiple Radio values with mysql

I've 10 question and each have 4 options, i want to check radio values, whether it is correct or not with the result stored in database when a user submit the form.
thanks in advance...
while($row = mysqli_fetch_array($result)){
foreach( $_POST as $key=>$val){
if($row['answer'] == $val){ echo "Correct";}
else{ echo "Incorrect";
}
#broken_heart is right. you should provide your code. then some body will guide you.... anyway, this is the one way.. try once...
Steps:
assign different names with auto increment for each radio button group. name should be like this radio_name[$i] .... here $i is auto increment...
submit the form
Get value like this..
$radio_values=$_POST['radion_name'];
for($i=0;$i<count($radio_values);$i++)
{
$radio_value= $radio_values[$i];
}

choosing user picked check boxes (dynamically created) in PHP

Hi I have a check box dynamically created as follows;(not the complete code here) there are a number of check boxes created, hence name is an array. (Is it right the way I have started the array inside <td></td>?)
while ($rec = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td class='tbldecor1'><input type='checkbox' name='delete[]' value='$Val1'></td>";
echo "</tr>";
}
I need to get the user selected check box values to a loop in order to delete the records selected. If I forget about the deleting part of it, to get the user selected values to a loop I used something like below;
$AA = $_POST['delete'];
while($AA == 'checked')
{
echo $AA; // trying to print the user checked options so that I can subsequently code to delete them.
}
but seems an erroneous approach! Can someone please give me an idea?
foreach($_POST['delete'] AS $key => $val) {
...
}
checkboxes which aren't checked in the form aren't submitted, so automatically you'll only get the checked checkboxes in the _POST data.
it's input field array which gives you all checked value into array in $_POST, so use following way
if(isset($_POST['delete'])) {
foreach($_POST['delete'] as $value){
echo $value;
//do stuff
}
}

How to assign different names for each text box when placed in a loop in php..?

I had generated few textboxes in a loop n named them differntly.. but the retrieving of data from those boxes is not working.. Please help me..
code for creating those textboxes
$i=0;
while($data=mysql_fetch_array( $sql ))
{
echo "<tr><td>".$data['idno']." </td><td>".$data['name'] . " </td><td>
<input type='text' name='obtmarks".$i."'></td></tr>"; $i++;
}
I have to retrieve that data n place it another table
code for retrieving the data
$i=0;
while($data=mysql_fetch_array( $sql1 ))
{
$as=mysql_query("INSERT INTO marks values('".$data['idno']."','".$data['name']."','".mysql_real_escape_string($_POST['obtmarks".$i."'])."')");
$i++; }
Please help me.. thank u in advance..
Assuming you print the textboxes in a form, and post the form back to the retrieval code:
You need to get the variable value from the post array:
$i=0;
while($data=mysql_fetch_array( $sql1 ))
{
var value = $_POST['obtmarks'.$i];
// insert into database
$i++;
}
(Be careful to use the exact same label, in your example you use obmarks and obtmarks.)
WARNING Don't store the value in your database without checking it!! Use prepared statements!!
What about this:
$as=mysql_query("INSERT INTO marks values('".$data['idno']."','".$data['name']."','".$_POST['obmarks'.$i]."')");
this is assuming you are passing your data through a form submit.

How to check a check box if it's value is in DATABASE. PHP

I have inserted some check box values in mysql database using PHP
And in the below image i have fetch the values:
Now i need the o/p like the below image: The values which i inserted in the database should be checked
Hope now its clear.
Thanks in advance..
You should have a table of available options (in this case, something like a cities table), and then a user-to-cities look-up table. Then you can loop over the cities, but also fetch which cities the user has checked.
A sample, without knowing your database structure, would be as follows:
$uid = $_SESSION['user']['id']; // your logged in user's ID
$cities = array();
// get an array of cities
$sql = "SELECT id, name FROM cities";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$cities[$row->id] = $row->name;
}
// get an array of cities user has checked
$sql = "SELECT DISTINCT city_id FROM users_cities WHERE user_id = '$uid'";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$checked[] = $row->city_id;
}
// this would be templated in a real world situation
foreach ($cities as $id => $name) {
$checked = "";
// check box if user has selected this city
if (in_array($checked, $id)) {
$checked = 'checked="checked" ';
}
echo '<input type="checkbox" name="city[]" value="'.$id.'" '.$checked.'/>';
}
If I understand you question properly, the obvious and simplest approach is that you need to fetch records from database and when producing HTML [in a loop ot something similar] check if that value exists in array to results. You haven't given us any examples of your DB structure or code, so you must figure it our yourself how to do it.
Usually, you insert the values into the database. After inserting, you should have access to the same values again. It's not clear how you set up your script, so let's assume you redirect to another script.
What you need to do is retrieve the values for the checkboxes from your database again. Then you know which are selected. This can be used to determine if your checkbox need to be checked or not.
Note:
I assume here that the result of your query is an array with
the selected Ids as a value.
I assume here that your fields are stored in the result of
some query and is basically an array
with Field Id as key and Field Name
as Value.
E.g., something like this:
<?php
// Retrieve values from database.
$resultArray = ... some code ... ;
?>
<?php foreach ($field_types as $field_name => $field_value): ?>
<input type="checkbox" name="<?php echo $field_name; ?>" value="<?php echo $field_value ?>" <?php if (in_array($field_name, $resultArray)) { echo 'checked'; }/>
<?php endforeach; ?>
This results in a checkbox which is checked, if the field_name is inside the result array (with your already checked results). Otherwise they're just rendered as unchecked checkboxes. Hope this is clear enough.

Categories