I've created a dynamic checkbox, but failed to display its value on another page. The work I have done is the following:
index.php
<form method="post" action="print.php">
<?php
$host="localhost";
$username="root";
$password="";
$database="checkbox";
mysql_connect($host,$username,$password);
mysql_select_db("$database");
//Create the query
$sql = "select test, rate FROM lab";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo <<<EOL
<input type="checkbox" name="name[]"value="$row['test']}/{$row['rate']}"/>
{$row['test']}-{$row['rate']}<br />
EOL;
}
?>
<br>
<input type="submit" name="submit" value="Add" />
</form>
I am trying to display the value on a secon page called print.php:
<?php
print $_POST['name'];
?>
You need to use print_r function to display all values in the array. Like
print_r($_POST['name']);
See What's happening in your code:-
You are naming your check box in array.
So when you will get the submission in php you will receive an array by the name as :- name[]
So $_POST['name'] will return an array in php.
when you use print method then it can only print variable value .
it can't print array or object . if you use print/echo method to print array/object it will just print their type.
So to print an array you can use print_r() method or you can use var_dump() to check what is in variable.
you can access array as you favourite way by any loop.
For more about print-r and var_dump please follow manual link
[php.net manual][1]
http://www.php.net/manual/en/function.var-dump.php
You will need some way for identifying which checkbox is checked. You have couple of options use and index for the variable and get it as index or identify it from the value.
Here i have added $rowNum as index for name.
$rowNum=0;
while($row = mysql_fetch_assoc($result)) {
echo <<<EOL
<input type="checkbox" name="name[$rowNum]"value="$row['test']}/{$row['rate']}"/>
{$row['test']}-{$row['rate']}<br />
EOL;
$rowNum++;
}
Here if you check the first and third checkbox only, at PHP you will get
$_POST['name'] = Array
(
[0] => test0/rate0
[2] => test2/rate2
)
If you are not using the $rowNum as in your code and selecting the same options as above, you will get the folowing output.
$_POST['name'] = Array
(
[0] => test0/rate0
[1] => test2/rate2
)
You can use the array like this at print.php
if (is_array($_POST['name'])){
foreach($_POST['name'] as $key=>$name){
echo $key, '=>', $name,'<br/>';
//Here $key is the array index and $name is the value of the checkbox
}
}
Related
Hi I am trying create a system for making my own invoices, and printing them, so I created inputs with a while loop, depending on the number of articles I have entered, using the code below
<?php
$cont=1;
$numero = $_REQUEST['numeroa'];
while($cont<=$numero) {
echo $cont;
echo " <input class='Descripcion$cont' placeholder='Descripcion :' />";
echo " <input class='Precio' name='precio$cont' placeholder='Precio :' onkeyup='AddInputs()' /><br>";
$cont++;
}
echo "<textarea name='comment' >Escriba sus comentarios....</textarea>";
session_start();
$_SESSION['cont']=$cont;
?>
This sends post info to another php page, so I get something like this on the url
http://localhost/pruebas/facturapdf.php?precio1=1&precio2=2&precio3=3&precio4=4&precio5=5
I tried to get the variables using this code but I had no success
session_start();
$contp=$_SESSION['cont'];
while($cont<=$contp) {
$articulos[$cont]=$_GET['precio$cont'];
echo $articulos[$cont];
$cont++;
}
Is there a way I can use the get method changing the number each loop??
If there isn't, how can I get all the variables, knowing they are different every time, depending on the user input
thanks in advance..
As already mentioned, you're using single quotes for when you should be using double..
$articulos[$cont] = $_GET["precio$cont"];
Further, you could actually pass in an array directly as query data rather than appending a count value and looping through them.
echo " <input class='Descripcion' placeholder='Descripcion :' />";
echo " <input class='Precio' name='precio[]' placeholder='Precio :' onkeyup='AddInputs()' /><br>";
Note that I've simply changed name='precio$cont' to name='precio[]'
you can then access this as an array when submitted
$precioArr = $_GET['precio'];
Just to demostrate
for($i = 0; $i < count($precioArr); $i++) {
echo $precioArr[$i];
}
So you could actually use this for the requirements that you mentioned
If there isn't, how can I get all the variables, knowing they are different every time, depending on the user input
This can be demonstrated using this code
<?php
echo "query data:<br>";
print_r($_GET['array']);
echo "<br>";
echo "query keys:<br>";
print_r(array_keys($_GET['array']));
?>
So if you had a form like so:
<form action="demo.php" method="GET">
<input name="array[2]" type="text" value="11">
<input name="array[4]" type="text" value="11">
<input name="submit" type="submit" value="Submit">
</form>
This would pass a query query of ?array[2]=11&array[4]=11, the result you'd get is:
query data:
Array ( [2] => 11 [4] => 11 )
query keys:
Array ( [0] => 2 [1] => 4 )
try:
<?php
session_start();
$contp=$_SESSION['cont'];
while($cont<=$contp) {
$articulos[$cont]=$_GET['precio'. $cont];
echo $articulos[$cont];
$cont++;
}
difference to the original: 'precio'. $cont
this will concat the value of the variable $cont to the string literal 'precio'.
what you wrote ('precio$cont') will always be the literal string it is. no variable used.
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 issues with creating an array and storing the info, I have a table with data that could be infinite in its number, a user will then select some options which will determine which of these values they can select (which again is an infinite number), these choices are then presented into a checkbox where i use this code
<?php foreach ( $results['detailsline'] as $detailsline )
{
$invoice_details = $detailsline->details_line;
echo $invoice_details;
echo '<input type="checkbox" name="invoice_details" value="'.$invoice_details.'"/>';
}
?>
So this should search through the options they previous choose, and sorts them into an array and then into checkboxs, but when i store the information is just saves the last box checked, I cant change the value of each input EG
echo '<input type="checkbox" name="invoice_details[value1]"
echo '<input type="checkbox" name="invoice_details[value2]"
Because I don't know how many values/checkboxes there will be.
I have also tried this
<?php foreach ( $results['detailsline'] as $detailsline )
{
$invoice_details[] = $detailsline->details_line;
echo $invoice_details[];
echo '<input type="checkbox" name="invoice_details[]" value="'.$invoice_details.'"/>';
}
?>
Changing the
$invoice_details
to
$invoice_details[]
but this will just store a value "Array" in my database and not the actual values.
Please can anyone help me?
Ian
Okey I think You should Try this:
<?php
$i=0;
foreach ( $results['detailsline'] as $detailsline )
{
$invoice_details = $detailsline->details_line;
echo $invoice_details;
echo '<input type="checkbox" name="invoice_details[$i]" value="'.$invoice_details.'"/>';
$i++;
}
?>
Try this
<?php foreach ( $results['detailsline'] as $detailsline )
{
$invoice_details = $detailsline->details_line;
echo $invoice_details;
echo '<input type="checkbox" name="invoice_details[]" value="'.$invoice_details.'"/>';
}
?>
Use <input type="checkbox" name="invoice_details[]">
In your code you can use serialize($invoice_details) for saving into DB and when using - unserialize($field_from_db).
First function returns string, so you can save it as string field, second function get the string and returns the whole array, so you can work with it.
but this will just store a value "Array" in my database and not the actual values.
think you tried to store Array as string so got that value
So may be needed to use implode/serialize/json_encode (Array) to store data?
Literally saying code $invoice_details[] = $detailsline->details_line; means take property details_line of an object $detailsline and insert its value as new element in array $invoice_details. Are you sure it is what you want?) Also I suppose that $detailsline is an array, but not the object (you trying to operate it as an object)
I got a html form which i loop like this:
for($i=0;$i<10;$i++){
echo '<input type="text" name="field'.$i.'">';
}
then i make and hidden input with a count var which says that there are 10 such input fields. but now i hav $field0 to $field9 and i do not know how i can get the input in a for loop again.
thanks for your help!
Use names like this in your input fields: ...'field['.$i.']'...
This way in your $_POST these will show up in an array for you, and you can loop over them like:
foreach ($_POST['field'] as $key => $value)
{
}
First of all you should use $_POST to get your form data. then you can make this by doing
for($i=0;$i<$_POST["count"];$i++) {
$var = $_GET["field".$i];
//do something
}
I assume that you have a count variable in $_POST["count"]
2nd you could better use Arrays in your looped form
<input type="text" name="field[0]">
then you have an array in $_POST["field"] with $_POST["field"][0] and $_POST["field"][1] etc...
but to answer just you wanted you can also use variable variables:
here a sample which should make this clear
$a1 = "What";
$a2 = " are";
$a3 = " you";
$a4 = " doing?";
for($i=1;$i<=4;$i++){
$txt .= ${"a".$i};
echo $txt;
}
takes as output
"What are you doing?"
:)
in your loop:
echo '<input type="text" name="field['.$i.']">';
then when you process this form when it's submitted:
$fields = $_POST['field'];
the "field" variable will be sent as an array to PHP
Let's imagine I got this:
index.php generates form with unpredictable number of inputs with certain IDs/Names and different values that can be edited by user and saved by script.php
<form action="script.php" method="post">
<input id="1" name="1" type="text" value="1"/>
<input id="24" name="24" type="text" value="2233"/>
<input id="55" name="55" type="text" value="231321"/>
</form>
Script.php:
Here I need to get something like array of all inputs that were generated by index.php and save every value that corresponds to its id/name.
Is there a way to do this?
i may be missing something in your question, but the $_POST variable will contain all the name => value pairs you're asking for. for example, in your above HTML snippet:
print_r($_POST);
// contains:
array
(
[1] => 1
[24] => 2233
[55] => 231321
)
// example access:
foreach($_POST as $name => $value) {
print "Name: {$name} Value: {$value} <br />";
}
Use an array_keys on the $_POST variable in script.php to pull out the names you created and use those to get the values.
$keys = array_keys( $_POST );
foreach( $keys as $key ) {
echo "Name=" . $key . " Value=" . $_POST[$key];
}
It sounds like you're using a class or framework to generate your forms, you need to read the documentation for the framework to see if/where it's collecting this data.