submit all users values from form into db - php

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];

Related

Using concatenated variables individually for database fields

I am new to stackoverflow and am after a little help. I have already tried searching for what I am about to ask, but cannot find any relevant topics, so here goes:
I have a PHP page, that gets a list of venues and it's town/city from a table within a MySQL database, which I have then concatenated to populate a dropdown, e.g. each <option> will display "[venue], [town/city]".
What I am trying to do is when the user selects one of the options, I want to store the [venue] and [town/city] as separate fields in another table within the MySQL database.
I would really appreciate any help.
More details might be needed. For instance do you need to know how to insert records on database? or are you also having trouble getting values of option tag?
But from what I understood:
First remember to set value attribute of option tags:
<option value="venue,town">venue,town</option>
Then after submitting the form, you can slice the returned string.
Assume you stored "venue,town" inside a variable named $str
$results = explode(",",$str);
$results will be an array with two elements. $results[0] contains "venue" and $results[1] contains "town"
I am not sure how much it helped but you can give more details and I'll get back
I think the best way is to put the datarecord ids (primary key value) into the value attribute of the <option> tags, then on the server side requery the data of the selected id from the database. This way your form can't be manipulated with unwanted data.
To be more clear, I would do it like in this simplified semi pseudocode:
<?php
$action = isset($_GET['action']) ? $_GET['action'] : null;
if($action == "save") {
$id = $_POST['venue'];
if(!empty($id)) {
/* fetch data belonging to $id from database and then save venue and town/city
as separate fields in another table */
}
}
/* fetch all data for the selectbox from the db and store it in $data */
?>
<form action="?action=save" method="post">
<select name="venue" size="1">
/* iterate through $data and create $id and $caption */
<option value="<?php echo $id; ?>"><?php echo $caption; ?></option>
/* iteration end */
</select>
<input type="submit" value="save" />
</form>

How to get the values of div using its id after retrieving the values from database using php

I am trying to get the values of div elements using Simple HTML Dom Parser. Its working fine for only hard coded values. Here is the hard coded stuff.
<table>
<tr><td class='none'><div class='drag' id='d1'>1</div></td></tr>
<tr><td class='none'><div class='drag' id='d2'>2</div></td></tr>
<tr><td class='none'><div class='drag' id='d3'>3</div></td></tr>
Apart from these constant values i need to get the other id values which are displayed based on the selection from the drop-down menu.
<form method="post" name="order" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select id='test' name='test'>
<option value="">Please Select</option>
<option value='test1'>Test1</option>
<option value='test2'>Test2</option>
</select>
</form>
After the selection they click the continue button which redirects them to the same page and here is my script that displays id's from database.
<?php
$i=4;
if ($_SERVER['REQUEST_METHOD']=="POST")
{
$query = mysql_query("select * from test_demo where test_requested='$_POST[test]'");
while($result=mysql_fetch_array($query))
{
echo "<tr><td class='none'><div class='drag' id='d$i'>". $result['oid'] ."</div></td></tr>";
$i++;
}
}
echo "</table>"
?>
Now i want to get the order id's 1,2,3 and remaining id's retrieved from the database. In order to get these values i am using a Values button on click goes to retrieve.php file.
In retrieve.php file i am using Simple html dom parser to get the values. Here is the code.
<?php
include_once('simple_html_dom.php');
//test.php contains my hard coded html and php code
$html = file_get_html('test.php');
$temp = '1';
//usig div name we are retrieving the values
foreach($html->find('div#d5') as $e)
$result[]= $e->innertext;
print_r($result);
?>
In the place of d5 if i could mention d1 or d2 or d3. I could able to get the values 1,2,3 respectively. But i am unable to get the order id values which are retrieved from the database. The div ids for these elements starts from d4 and so on. Where could be I am going wrong?
There are several issues.
First, PHP scripts aren't run if you access them as ordinary files. You need to change the URL to go through the server:
$html = file_get_html('http://localhost/path/to/test.php');
Second, you need to provide the value of the test parameter in the URL, so it should be:
$html = file_get_html('http://localhost/path/to/test.php?test=test1');
Third, in test.php you need to access the parameter using $_GET, not $_POST, when it's accessed this way:
if ($_SERVER['REQUEST_METHOD'] == "GET") {
$test = mysql_real_escape_string($_GET['test']);
$query = mysql_query("select * from test_demo where test_requested='$test'");
...
}

PHP avoiding a long POST

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);
}
}

check if checkbox is checked in php

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
}
?>

Help with a function php

I want a function that prints those 2 "print" in the database ( insert intro ) when a button is pressed.
Here's the code:
<?php
$id2name=array();
$x=mysql_query("SELECT id,name FROM products WHERE id IN(".implode(',',array_keys($_SESSION['cart'])).")");
while($y=mysql_fetch_assoc($x)){
$id2name[$y['id']]=$y['name'];
}
foreach($_SESSION['cart'] as $k=>$v){
print "<br>[".$id2name[$k]."]\t".$v."\n <br>";
}
print "<br>$total<br>";
?>
How can I make that a function, to print it in the database when a button is pressed?
Not sure if I got you right, but as far as I understand, you want to write something to the database by pressing a button, right?
Well, to trigger an action by pressing a button, you need a form:
<form action="page_to_process_the_db_request.php" method="post">
<input type="hidden" value="<?php echo $total;?>" name="total" />
<input type="submit" value="Wirite to DB!" />
</form>
In this example, I assume you want to write the variable $total to DB.
So you post the data to the processing page (which also can be the same one you're on) and there, you look if there's something in the $_POST-array:
<?php
if(isset($_POST['total'])) {
mysql_query("UPDATE products SET total = ". $total); //or something like that
}
?>
Not sure though if this is what you're looking for...
//edit
referring to your comment, I guess you want to write the output of the loop to DB...
At first, you have to create an appropriate structure, like an array:
foreach($_SESSION['cart'] as $k=>$v){
$id2name[$k]['name'] = $v;
}
now you can turn the array into a simple string with
$serialized_array = serialize($id2name);
And now you can write this string to db. And when you read it from db, you can turn it back into an array again with:
$id2name_array = unserialize($serialized_array);

Categories