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
}
?>
Related
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've created a test system that has multiple steps (using jquery) allowing users to check checkboxes to select their answers, with a summary page and a final submission button... all within a form. I now want to create the scoring system.
1) Firstly this is the code (within a loop) that grabs the answers from Wordpress for each question:
<input type="checkbox" name="answer<?php echo $counter; ?>[]" value="<?php echo $row['answer']; ?>" />
2) In Wordpress next to each answer is a dropdown with a yes or no option to mark whether the answer is right or wrong. This is output in the following way:
<?php $row['correct']; ?>
3) Each correct answer the user checks should be worth 1 point. The passmark is determined by the field:
<?php the_field('pass_mark'); ?>
4) I want it to update a hidden field with the score as the user checks the correct answer:
<input type="hidden" value="<?php echo $score; ?>" name="test-score" />
How can I update the hidden field with the user score as the user is checking the correct answer? I'm not sure what to try with this to even give it a go first!
Ok, everyones spotted a big hole in this. I'm completely open to doing it a hidden way so people can't check out the source. The type of user this is targeted at wouldn't have a clue how to look at the source but might as well do it the right way to start with!
The whole test is within a form so could it only update the hidden field on submit?
I still need some examples of how to do it.
In my opinion you should use sessions for that purpose, because any browser output may be saved and viewed in ANY text editor. This is not right purpose oh hidden input elements. You use hidden inputs when you need to submit something automatically, but never use it when processing some important data.
Mapping your questions and answers via id will allow you not to reveal real answers and scores in HTML.
Just a very simple example how to do that:
<?php
$questions = array(
125 => array("text"=>"2x2?", "answer"=>"4", 'points'=>3),
145 => array("text"=>"5x6?", "answer"=>"30", 'points'=>2),
);
?>
<form method="post">
<?php foreach ($questions as $id => $question): ?>
<div><?php echo $question['text'] ; ?></div>
<input type="text" name="question<?php echo $id ; ?>"/>
<?php endforeach ; ?>
<input type="submit" value="Submit"/>
</form>
/* In submission script */
<?php
if (isset($_POST['submit'])){
foreach($questions as $id => $question){
if (isset($_POST["question{$id}"])){
$answer = $_POST["question{$id}"] ;
if ($answer === $question['answer']){
$_SESSION['score'] += $question['points'] ;
}
}
}
}
Spokey is right - the user would be able to cheat if your score it on the client side like using the method you suggested.
Instead, either user a JQuery $.post call to post each answer and then store the score in a PHP Session. Or just wait until the entire form is submitted and evaluate the score of the form as a whole on the server side.
* Update *
You have to submit the form to a script that can evaluate the form. So say it gets submitted to myForm.php
In myForm.php, get the post vars:
$correct_answers = $however_you_get_your_correct_answers();
//Assuming $correct_answers is a associative array with the same keys being used in post -
$results = array();
if($_POST){
foreach ($_POST as $key=>$value) {
if ($_POST[$key] == $correct_answers[$key]){
$results[$key] = 'correct';
}
else $results[$key] = 'incorrect';
}
}
This is untested, but it should work.
This is more of a technique question rather than maybe code. I am having a php form with many fields (items to select). Naturally some of the items might be selected and some not. How do I know which ones are selected when i post the data from page 1 to page 2? I thought of testing each one if empty or not, but there are just too many fields and it doesn't feel at all efficient to use or code.
Thanks,
UPDATE EDIT:
I've tried the following and maybe it will get me somewhere before I carry on testing the repliers solutions...
<html>
<body>
<form name="test" id="name" action="testprocess.php" method="POST">
<input type="text" name="choices[shirt]">
<input type="text" name="choices[pants]">
<input type="text" name="choices[tie]">
<input type="text" name="choices[socks]">
<input type="submit" value="submit data" />
</form>
</body>
</html>
and then second page:
<?php
$names = $_POST['choices'];
echo "Names are: <br>";
print_r($names);
?>
This gives out the following:
Names are: Array ( [shirt] => sdjalskdjlk [pants] => lkjlkjlk [tie]
=> jlk [socks] => lkjlkjl )
Now what I am going to try to do is iterate over the array, and since the values in my case are numbers, I will just check which of the fields are > 0 given the default is 0. I hope this works...if not then I will let you know :)
I think what you're looking for is this:
<form action="submit.php" method="POST">
<input type="checkbox" name="checkboxes[]" value="this" /> This
<input type="checkbox" name="checkboxes[]" value="might" /> might
<input type="checkbox" name="checkboxes[]" value="work" /> work
<input type="submit" />
</form>
And then in submit.php, you simply write:
<?php
foreach($_POST['checkboxes'] as $value) {
echo "{$value} was checked!";
}
?>
The square brackets in the name of the checkbox elements tell PHP to put all elements with this name into the same array, in this case $_POST['checkboxes'], though you could call the checkboxes anything you like, of course.
You should post your code so we would better understand what you want to do.
But from what I understood you are making a form with check boxes. If you want to see if the check boxes are selected, you can go like this:
if(!$_POST['checkbox1'] && !$_POST['checkbox2'] && !$_POST['checkbox3'])
This looks if all the three check boxes are empty.
Just an idea:
Create a hidden input field within your form with no value. Whenever any of the forms fields is filled/selected, you add the name attribute of that field in this hidden field (Field names are saved with a comma separator).
On doing a POST, you can read this variable and only those fields present in this have been selected/filled in the form.
Hope this helps.
Try this.....
<?php
function checkvalue($val) {
if($val != "") return true;
else return false;
}
if(isset($_POST['submit'])) {
$values = array_filter(($_POST), "checkvalue");
$set_values = array_keys($values);
}
?>
In this manner you can get all the values that has been set in an array..
I'm not exactly sure to understand your intention. I assume that you have multiple form fields you'd like to part into different Web pages (e.g. a typical survey form).
If this is the case use sessions to store the different data of your forms until the "final submit button" (e.g. on the last page) has been pressed.
How do I know which ones are selected when i post the data from page 1 to page 2?
is a different question from how to avoid a large POST to PHP.
Assuming this is a table of data...
Just update everything regardless (if you've got the primary / unique keys set correctly)
Use Ajax to update individual rows as they are changed at the front end
Use Javascript to set a flag within each row when the data in that row is modified
Or store a representation of the existing data for each row as a hidden field for the row, on submission e.g.
print "<form....><table>\n";
foreach ($row as $id=>$r) {
print "<tr><td><input type='hidden' name='prev[$id]' value='"
. md5(serialize($r)) . "'>...
}
...at the receiving end...
foreach ($_POST['prev'] as $id=>$prev) {
$sent_back=array( /* the field values in the row */ );
if (md5(serialize($sent_back)) != $prev) {
// data has changed
update_record($id, $sent_back);
}
}
i have a form field
<input type="checkbox" name="page" value=""/>
and corresponding field in mysql db is true and false, if someone click the checkbox i would like to send TRUE value to db via POST, how do i achieve it ?
You give the input any value you like:
<input type="checkbox" name="page" value="true"/>
Then, if the checkbox is checked, it will be a successful control and submitted.
<?php
if (isset($_POST['page']) && $_POST['page'] == 'true') {
// Then insert something into the database as normal
}
?>
If you want to set it when the checkbox is not ticked, then you will need an else to go with the if.
For a checkbox, the value attribute determines what the value will be if the item is checked. If it isn't checked, then no value will be submitted at all. You should therefore always specify the value attribute on a checkbox.
If you want the checkbox to default to checked, then you also need to specify the checked attribute.
<input type="checkbox" name="page" value="1" checked='checked' />
The Form:
<form action="/path/to/processing_script.php" method="POST">
<!--... Other Form Elements go here -->
<input type="text" name="color" />
<input type="checkbox" name="page" value="True"/>
<input type="submit" value="Send to Database" />
</form>
Processing script:
(processing_script.php)
<?php
// Check is 'True'?
if ($_POST['page'] != 'True')
{
$_POST['page'] = 'False';
}
$con=mysqli_connect("your-db-loc","your-db-username","your-db-pass","db-name");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL Database: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO TableNameHere (True-false, Favorite Color)
VALUES ($_POST['page'], $_POST['color'])");
mysqli_close($con);
?>
This example I created add's 2 data types to a new row on the database.
Replace the text 'TableNameHere' with your db table name, should be in similar format to: 'prefix_colors_tble'
Replace the text "your-db-loc" with your databases location, usually 'localhost' for internal server, or could be a URL for live server.
Replace the text "your-db-username" the username used to login to mysql, must have sufficient privileges.
Replace the text "your-db-pass" the user's password
Replace the text "db-name" database name (not deemed important unless containing multiple databases)
Replace the text "True-false" & "Favourite Color" with your db table column headings as appropriate.
Good Luck! -p.s. I know this answer is a few years late, but I hope it can help somebody else. Send your appreciation to http://amazewebs.com/testimonial Thanks.
Collect the follows by reading $_POST after form submission, then write them to the database using mysql_query
the first thing you will have to do is to modify the current html code for checkbox and add something in the value field.
let say you set the value to 1.
The second thing is if you are posting the form, then you will have to process the form using a server side language like PHP,Perl, Java etc.
for e.g. in PHP you can get the catch what is sent for the page field using $_POST['page'].
Now you will have to do a bit of server side processing to see if the $_POST['page'] == '1' , then set $page = 'true';else set$page = 'false';
the you can insert the $page into the database by using the library functions of the language you are using.
I've got the following php code printing out the contents of a SQL table.
$query="select * from TABLE";
$rt=mysql_query($query);
echo mysql_error();
mysql_close();
?>
<i>Name, Message, Type, Lat, Lng, File </i><br/><br/>
<?php
while($nt=mysql_fetch_array($rt)){
if($nt[name] != null){
echo "$nt[id] $nt[name] $nt[message] $nt[type] $nt[lat] $nt[lng] $nt[file]";
}
}
?>
How would I implement a button so for each "row" if the button is clicked on that row it'll submit the information of that row to another php file?
I want it looking something like...
details details2 details3 BUTTON
details4 details5 details6 BUTTON
details7 details8 details9 BUTTON
details10 details11 details12 BUTTON
Where if BUTTON was hit on row 1 details1,2,3 would be sent to a php file, on row 2 detals 4,5,6 would be sent etc. How would I do this?
Thanks.
it's going to be something like that, depending on the data you need to send:
while($nt = mysql_fetch_array($rt)) {
if($nt[name] != null){
echo "$nt[id] $nt[name] $nt[message] $nt[type] $nt[lat] $nt[lng] $nt[file] ".'send request<br/>';
}
}
You can either use GET method and send a query string to the second php page and receive the variables there, like
next.php?variable1=value1&variable2=value2&...
or use POST method by making a hidden form for each row and assign a hidden field for each variable you want to send.
<form method="post" action"next.php">
<input type="hidden" name="variable1" value="value1" />
<input type="hidden" name="variable2" value="value2" />
.
.
.
</form>
or instead of sending all the values, just send the row ID (if any) using any of these two methods and run another query in next.php to get the information you need from database.
Instead of submitting the entire data, just send the ID and fetch the results from the database in the other script. If you want to have an input button, you can do
<form action="/other-script.php" method="GET">
<?php printf('<input type="submit" name="id" value="%s" />', $nt["id"]); ?>
</form>
but you could also just add a link, e.g.
printf('Submit ID', $nt["id"]);
If you really want to send the entire row values over again, you have to make them into form inputs. In that case, I'd send them via POST though.