Here is a quickie obviously unworking code of an example of what I am looking to do.
Lets say this is a dinner menu, and the echo's are currently all the foods that are stored in the database. The user selects only the foods they want, and those selections are inserted into another table.
EXAMPLE:
<form method="post" action="entryform3.php">
<?php
SELECT * FROM foods ...etc...etc...
//Say for example whats echoed below at the moment is value: pizza, apple, steak...etc. So this will echo atleast 3 entries.
echo "For dinner, I'd like ". $result['food'] ."?";
echo "<input type=\"checkbox\" name=\"check\" />Click Me<hr></input>";
echo "<input type=\"hidden\" name=\"item_name\" value=\"$result['food']\"/>";
?>
<input type="submit" value="Add Selected Foods" name="submit"></form>
------------entryform3.php-----------
<?php
$food = $_POST['food'];
if (isset($_POST['check'])) {
INSERT INTO selectedfoods "(foods) VALUES '$food'";
}
//made up example... but if user check marks only apple, and steak from the echo, I want only apple and steak to be inserted into database.
?>
I realize there is missing mysql and such, but my problem lies in tying together the checkbox button with an individual value. My partially working code that I took this example from, only takes the very last echoed selection, if any one of the foods is checked.
So, it doesn't send the correct food choice into the database, only the last echoed --the if statement only notices if any one of the check boxes are selected or not.
Thanks!
It seems like you miss the name of the checkbox as array. For example, you may write your checkbox like this:
<input type="checkbox" name="box[]" value="name_of_food" />Name_of_Food<br />
.......
.......
then when you get the result, just do like this:
<?php
if(isset($_POST['check'])){
$foods = $_POST['box'];
foreach($foods as $food){
echo $food." <br />";
}
}
?>
Related
I have a variable number of fields in a table,where the number of column headings are directly fetched from database,so the number of heading increases as the data from database increase(eg-demo,demo1,demo2,..).For each column there is a selectbox,here i have given name for check box as txtcheck".$i."[] where $i is set as an incriminating value.
<input type='checkbox' name='txtcheck".$i."[]' value='1'>
My doubt is how can i fetch the checkbox post value when form submission.I dont know whether this is correct way nor find a way to efficiently do this. Please advise.
The name of your checkboxes shouldn't be incremented, but only be txtcheck[]. In this case the selected boxes will be transfered as array.
<input type='checkbox' name='txtcheck[]' value='1' />
In your PHP code you can access this array with $_POST['txtcheck'].
<?php
$checkedBoxes = $_POST['txtcheck'];
foreach ($checkedBoxes as $checkdBox) {
// Here you can handle each box that was checked in your form, e.g. echo it's value
echo $checkedBox . ' ';
}
?>
So if you checked e.g. boxes with values 1, 5 and 10 your output will be 1 5 10
I have a table of questions, and I'd like to use a foreach loop to print out each question separately with a text box and a checkbox next to it. I then need to be able to take any question that is checked and do stuff to them--specifically, take the id of the question and place that in a junction table, as these questions are to be added to a printable file. (It's a test question database). I know how to do foreach loops, but I was wondering if this was possible, and how to iterate the values to make sure each textbox corresponds to a checkbox and the right values are obtainable.
I hope that makes sense.
You should just be able to do something like this:
(except that this is not a For Each loop, same concept applies)
<? for ($xlist=0; $xlist<9; $xlist++) { ?>
<input type="checkbox" name="checkSel" id="check_<? =xlist ?>"> <input type="text" value="<? =$yourValue ?>" name="quest" id="quest_<? =xlist ?>">
<? } ?>
That will paint out a checkbox and a question with the same identifier. That way you can make sure they relate to each other.
Create an incrementing integer for your loop and put this inside:
echo "<input type='checkbox' name='" . $loopIncrementVariable . "' value='" . $valueFromDatabase"'>";
You can do the same for the textbox, assigning it the same incrementing value from the loop. They will then both have the same id which can be used to match each other.
This gives lists all people in the db and give a drop down for each one of them i want to make it so when i hit one submit button it enters individual values for each person.
so if you make yes for bobby no for mark and yes for dustin you can the pres submit and it will enter that for there values
$results = mysql_query("SELECT * FROM `$tabeluser` WHERE buss='$buss' ORDER BY id DESC LIMIT 1");
while($rows = mysql_fetch_array($results) )
{
fn = $_POST['firstname'];
echo $fn;
?>
<form>
<select name="check">
<option>no</option>
<option>yes</option>
</select>
<?php
<input type="submit" name="submit">
?>
<form>
<?php
}
mysql_query("INSERT INTO `$fn` (buss) VALUES ('$_POST[check]')");
First of all, you create a <form> and a submit button for each of the records you have. That is wrong, since you want to update multiple values at once.
What it should look like would be:
<form>
<?php
while($rows = mysql_fetch_array($results)) {
print '<select name="check[]"> .. </select>';
}
?>
<input type="submit" name="submit" />
</form>
Secondly, your code is formatted as if you are expecting to get $_POST[check] right after sending the code to the browser. That is not how PHP works. You need to separate the logic of having posted values, before printing the actual page contents. PHP is server side, which means that it won't get any data, unless the script is called with it from the beginning. So, that should look something like:
<?php
if (isset($_POST["check"])) {
// handle posted data.
}
else {
// show form
}
// or show form here, without an else, if you want to always show a form,
// even when you have posted values.
?>
Last but not least, you need to find a way to know which posted value belongs to each of your records. The way you have it now (<select name="check">') it will just return you one single value.
If you write it the way I intentionally did above (`) you will get all values, but still you won't be able to easily recognize which value is for each record.
Instead, you may want to do a final result of something like:
<?php
// get mysql records into an array (say $my_array)
if (isset($_POST["submit"])) {
foreach($my_array as $record) {
if (isset($_POST["select_of_id_".$record["id"])) {
// insert additional value into db
}
}
}
print '<form>';
foreach($my_array as $record) {
print '<select name="select_of_id_'.$record["id"].'">';
print '<option value="0">no</option><option value="1">yes</option>';
print '</select>';
}
print '<input type="submit" name="submit"/>';
print '</form>';
?>
Changes required in your code :-
<select name="check[]">
<option value="<?php echo $userId;?>_0">no</option>
<option value="<?php echo $userId;?>_1">yes</option>
</select>
You should make changes in you DB It help to easy maintaing your data.
Create new table where you can save multiple user check data with respective Post
for e.g post_id user_id check
101 111 0
101 112 1
How you can store data from you html
In you post array you will get check array in which you will get multiple check value like this
101_0 if no selected and 102_1 if yes selected. Now you need to explode this value.
$_POST['check'] = array(0 => `101_0`, 1 => 102_1);
Inside loop you can extract userid and respective checked value.
for e.g
$checked = explode('_','101_0');
$userId = $checked[0];
$check = $checked[1];
I have a check box list which I fill it with data from my table.Here is the code:
<?php
mysql_connect("localhost","root","");
mysql_select_db("erp");
$a="Select * from magazine";
$b=mysql_query($a);
$c=mysql_fetch_array($b);
while($c=mysql_fetch_array($b))
{
print '<input type="checkbox"/>'.$c['den_mag'];
echo "</br>";
}
if(isset($_POST['den_mag']))
{
echo "aaaa";
}
?>
It's a simple query and for each data just show it with a checkbox.Now what I want is when I press a checkbox the value of that checkbox to be shown in a table.So if I have check1 with value a , check2 with value b and I check check1 the value a to be outputted to a table row.How can I achieve that? how cand I get which checkbox is checked?
A few notes:
Try to avoid using SELECT * queries. Select the fields you are going to use:
$sql= '
SELECT
id,
den_mag
FROM
magazine
';
Use better variable names. $a and $c make your code harder to follow for others, and for yourself when you come back at a later time. Use more descriptive variable names like $query_object and $row. Your code should read almost like an essay describing what you're doing.
In your form, use an array of elements. By giving the input a name like selected_magazines[], you will end up with an array in your post data, which is what you want -- multiple selections
Use the row ID as the value of the checkbox element. Your array in POST will then be a list of all the IDs that the user selected
Separate your logic from your HTML generation. The top portion of your script should take care of all logic and decisions. At the bottom, output your HTML and avoid making logical decisions. It makes for a script that is easier to follow and maintain, as well as debug.
Here is a sample script incorporating these ideas with the details you've given:
<?php
// FILE: myfile.php
mysql_connect("localhost","root","");
mysql_select_db("erp");
if(isset($_POST['selected_magazine'])) {
// $_POST['selected_magazine'] will contain selected IDs
print 'You selected: ';
print '<ul><li>'.implode($_POST['selected_magazine'], '</li><li>').'</li></ul>';
die();
}
$sql= '
SELECT
`id`,
`den_mag`
FROM
`magazine`
';
$query_object=mysql_query($sql);
$checkboxes = array();
while($row = mysql_fetch_array($query_object)) {
$checkboxes[] = '<input name="selected_magazine[]" value="'.$row['id'].'" type="checkbox" /> '.$row['den_mag'];
}
?>
<form action="myfile.php" method="post">
<?php print implode('<br>', $checkboxes); ?>
<input type="submit" value="Submit" />
</form>
<input name="test" type="checkbox" />
<?php
if(isset($_REQUEST['test'])){
// selected
}
?>
When you give input-type elements (input, textarea, select, button) a name attribute (like I did), the browser will submit the state/value of the element to the server (if the containing form has been submitted).
In case of checkboxes, you don't really need to check the value, but just that it exists. If the checkbox is not selected, it won't be set.
Also, you need to understand the client-server flow. PHP can't check for something if the client does not send it.
And finally, someone mentioned jQuery. jQuery is plain javascript with perhaps some added sugar. But the point is, you could in theory change stuff with jQuery so that it gets (or doesn't get) submitted with the request. For example, you could get jQuery to destroy the checkbox before the form is submitted (the checkbox won't be sent in this case).
Here you go :
<html>
<input name="test" value="true" type="checkbox" />
</html>
<?php
$Checkbox1 = "{$_POST['test']}";
if($Checkbox1 == 'true'){
// yes, it is checked
}
?>
I have written the following code in PHP to generate two dropdown boxes on the same page.
The first dropdown box gets value from a MySQL table. This dropdpwn box contains some UserIDs. The second dropdown box contains some dates which should be based on the UserID that is selected in the first dropdown box. I have filled the 2nd dropdown box with all the dates in the MySQL table, but, it should be filtered by the UserID which is selected on the first dropdown box.
Just to inform, with these two values from these two dropdown boxes in this PHP page, I have posted them by pressing the submit button to another PHP page to process some other work.
I would appreciate if you can help me to fill the second dropbox only based on the UserID selected on the first dropbox. Here is the code I have written to display and fill those dropdown boxes. Can you please inform me, what part of the code I should modify and I would appreciate if you can show me the modification code as well. I am a newbie in PHP, that's why I am asking for code level help.
My code:
<html>
<head>
<title>
Search Alert DB
</title>
<body>
<br />
<?php>
$con = mysql_connect("localhost","root","root"); // (host, user,pwd)
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mysql", $con);
echo "<p> Search Alert database </p>";
echo "<br />";
$result = mysql_query("SELECT distinct(UserID) FROM tblAlertLogSpecificUsersDayStatusFinal_1");
$options="";
echo "<form action='Search_AlertDB_process.php' method='POST'>\n";
//echo "Please choose a user: ";
echo "Please choose a user: <select name = userid>";
echo "<option>-Select-";
while ($row = mysql_fetch_array($result))
{
$userid=$row["UserID"];
$options ="<option value = \"$userid\">$userid </option>";
echo "$options";
}
echo "</select>";
echo "<br />";
echo "<br />";
$dayresult = mysql_query("SELECT distinct(Occurred_date) FROM tblAlertLogSpecificUsersDayStatusFinal_1");
$dayoptions="";
echo "Please pick a date:<select name = day>";
echo "<option>-Select-";
while ($row=mysql_fetch_array($dayresult)) {
$day=$row["Occurred_date"];
$dayoptions ="<option value = \"$day\">$day </option>";
echo "$dayoptions";
//$options.="<OPTION VALUE=\"$id\">".$day;
}
echo "</select>";
echo "<br />";
mysql_close($con);
?>
<br />
<input type="submit" name="Submit" value="Search" /> <br /> <br />
</form>
</body>
</html>
You'll need 3 things
Initial page with select fields
The first select field is pre-populated with user ids
The second field contains no options and is disabled
A separate endpoint/page that takes a user id as a parameter to return relevant dates
It should probably return JSON/XML (or something similar), or you could return the dates pre-rendered in <option /> tags (shouldn't really do this, but it would be quicker to hack this together)
Javascript callback triggered when an option in the first dropdown is selected. The callback should send an AJAX request to the separate endpoint and populate the second dropdown with the result.
It would have probably been easier for me to write it all out for you than [try] to explain it, but that's not really the point. Just trying to set this all up (all be it; relatively simple) will teach you a whole load of things about Javascript, AJAX and web services.
If you choose to return JSON/XML from your web service (the separate endpoint/page), and hopefully you will, you might also start to see the benefit of separating logic from presentation, which will make the world of difference to both your understanding and delivery of code.
Well, we wont write the code for you. Otherwise you are going to be newbie for all your life :)
What you need here is called AJAX. The easiest way to implement it is probably jQuery ajax function. If you don't know jQuery - learn the basics, it shouldn't take more than an hour or so. It's worth it :)