I have a dynamic web form that creates text after the user tells it how many he wants, what I want to do, is to get the info of those text fields into the next form, I've read a question that is
pretty much what I want to do;
But I haven't had any luck so far;
for ($i = 1; $i <= $quantity; $i++) {
echo "<input type='text' class='text' name='classEmpleado[]' id='empleado$i' />";}
When I try to retrieve them I use this;
$empleado[] = $_POST['classEmpleado[]'];
$i = 0;
for ($i = 1; $i <= $quantity; $i++) {
echo "$empleado[$i]<BR><BR>";
}
But I get the error Undefined index: classEmpleado[]
What am I doing wrong?
ANSWERED!
For anyone looking for the same thing, look at the response of Sherbrow,
And you would just have to edit the loop to this
$empleado[] = $_POST['classEmpleado[]'];
$i = 0;
for ($i = 0; $i < $quantity; $i++) {
echo "$empleado[$i]<BR><BR>";
}
If $empleado is not previously declared or just empty, you are looking for that
$empleado = $_POST['classEmpleado']
But if $empleado is an array, and contains data, you may want to merge everything in one only array
$empleado = array_merge($empleado, $_POST['classEmpleado']);
Whichever way you choose, there should be a check to be certain that $_POST['classEmpleado'] is defined and is an array. Something like :
if(isset($_POST['classEmpleado']) && is_array($_POST['classEmpleado'])) {
/* ... */
}
Try $empleado[] = $_POST['classEmpleado'];
When you put name[] at the end of the fieldname, it will be passed to PHP as an array in $_POST with the key of name like so: $_POST['name'] = array(1,2,3,4);
This statement here is wrong ($empleado[] = $_POST['classEmpleado[]'])
If you want to access $_POST the input field named classEmpleado[], you have to do so :
for($i=0; $i<count($_POST['classEmpleado']); $i++)
{
echo $_POST['classEmpleado'][$i] . '<br /><br />';
}
Related
I've got a form which asks some basic questions about a job, and then asks to person entering to list all those colleagues that were with them at the time. What I want to do is for all colleagues present to have a row entered in to the database - so all the other details remain the same except for their work_id (which is the identifier for the person). My code below seems to submit 1 row to the db with the workID field empty
<?php
require_once('includes/dbconnect.php');
$varWorkID = $_POST['workid'];
$varDate = $_POST['date'];
$varType = $_POST['type'];
$varSuper = $_POST['supervisor'];
$varReference = $_POST['reference'];
//Remove last part of array as extra 1 sent through by form
$workID = array_pop($varWorkID);
for ($i=0; $i < count($workID); $i++ )
{
mysqli_query($conn,"INSERT INTO searches (workid,date,type,super,reference) VALUES('".$workID."','".$varDate."','".$varType."','".$varSuper."','".$varReference."')");
}
echo "Completed";
I think I'm fairly close but I just need to get workid to be populated with each of the Work IDs for each of the employees present.
Any assistance greatly appreciated
the problem here is that you're calling $workID = array_pop($varWorkID); before you go into the loop for ($i=0; $i < count($workID); $i++ ), so the PHP interpreter thinks you just want to iterate over the length of that one element. what you actually wanted to do was pop an element off the array while inside the loop.
<?php
require_once('includes/dbconnect.php');
$varWorkID = $_POST['workid'];
$varDate = $_POST['date'];
$varType = $_POST['type'];
$varSuper = $_POST['supervisor'];
$varReference = $_POST['reference'];
// iterate over the count of the whole array $varWorkID = $_POST['workid']
for ($i=0; $i < count($varWorkID); $i++ )
{
// now pop off the array inside the loop
//Remove last part of array as extra 1 sent through by form
$workID = array_pop($varWorkID);
mysqli_query($conn,"INSERT INTO searches (workid,date,type,super,reference) VALUES('".$workID."','".$varDate."','".$varType."','".$varSuper."','".$varReference."')");
}
echo "Completed";
now I think #Dima Fitiskin's comment proposes a better approach because you don't really need the expense of calling another function array_pop or throwing another variable on the stack $workID when you've already got an iterated reference to the index $i inside the loop.
<?php
require_once('includes/dbconnect.php');
$varWorkID = $_POST['workid'];
$varDate = $_POST['date'];
$varType = $_POST['type'];
$varSuper = $_POST['supervisor'];
$varReference = $_POST['reference'];
// iterate over the count of the whole array $varWorkID = $_POST['workid']
for ($i=0; $i < count($varWorkID); $i++ )
{
mysqli_query($conn,"INSERT INTO searches (workid,date,type,super,reference) VALUES('".$varWorkID[$i]."','".$varDate."','".$varType."','".$varSuper."','".$varReference."')");
}
echo "Completed";
i have the var $products who reads the id and twelve products from a mysql row in a array. No i want that only the fields who have text will be displayd. I wrote it with a "for" and it works, but how can i tell the code to stop, after the array is getting empty? "p" is to generate the db field name who is p1, p2 and so on.
for($i=1; $i < count($products); $i++)
{
echo "<div>Produkt ".$i":</div>
<div>".$products["p".$i]</div>"
}
Are you looking for something like this:
<?php
for($i=1; $i < count($products); $i++)
{
if($products["p".$i] !=""){
echo "<div>Produkt ".$i.":</div>";
echo "<div>".$products["p".$i]."</div>";
}
}
?>
I have a checkbox table declared like this:
for ($x = 0; $x < 6; $x++) {
echo "<tr>";
echo "<td>"; echo $days[$x]; echo '</td>'; //displays days
echo '<td><input type="checkbox" name="check_list[]" onClick="toggle(this, '.$x.')" value="1"/> All';
echo '<input type="hidden" name="check_list[]" onClick="toggle(this, '.$x.')" value="0"/></td>'; //creates check all buttons
for ($y = 0; $y < 12; $y++){
echo '<td><input type="checkbox" name="'.$x.'" value="1"> Bar 1<br/></td>'; //creates the other buttons
}
echo "</tr>";
}
The name="check_list[]" checkbox selects all the checkboxes in the same row when checked. It is done with this script:
<script language="JavaScript">
function toggle(source, id) {
checkboxes = document.getElementsByName(id);
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
Then the data are stored like this in the database:
<?php
$i=0; $store[20]; $check[20];
foreach($_POST['check_list'] as $value){
$store[$i] = $value; $i= $i + 1;
}
$check = str_split(preg_replace('/10/','1',implode('',$store)));
array_walk($check, 'intval');
if($check[0]) { $monday = 1; } if(!$check[0]) {$monday = 2; }
if($check[1]) { $tuesday = 1; } if(!$check[1]) {$tuesday = 2; }
if($check[2]) { $wednesday = 1; } if(!$check[2]) {$wednesday = 2; }
if($check[3]) { $thursday = 1; } if(!$check[3]) {$thursday = 2; }
if($check[4]) { $friday = 1; } if(!$check[4]) {$friday = 2; }
if($check[5]) { $saturday = 1; } if(!$check[5]) {$saturday = 2; }
?>
Obviously, this is not the whole code (I wrote the sql query to connect and insert the variables for the days. And it worked). But till now I am only taking the values of the first checkbox for each row. Which means that if I check it, all the checkboxes of that row are checked. But I am only reading the fact that all the checkboxes of that row are checked. If I only check a normal checkbox in a row, its value is not posted and I the only info stored is that not all checkboxes are checked (represented by value 2).
What I want to do is take the value of the normal checkboxes for each row instead, and concatenate them in a number. For example, for monday checkboxes (checked, unchecked, unchecked, checked) i would store $monday = 1221.
The same must be done for all days (monday to saturday)
You can do as follows:
for ($y = 0; $y < 12; $y++){
<input type="text" name="matrix['.$x.']['.$y.']" value="Text" />
}
And in your sever:
foreach($_POST['matrix'] as $key => $value) {
echo $key;// Value of $x
foreach($value as $k => $val) {
echo $k;// This would be the value of $y
echo $val;// This would be the value of the inputs
}
}
The way you describe it, it is not possible. It is not possible to put an array declaration as a variable name. However, I somewhat get (and assume) a picture of what you want to do.
After creating the input elements dynamically, also create a hidden input element that contains the "count" of how many elements where created. Then, in PHP code, first access the count element to find out how many elements are present. Then, loop through that index, to build the loop name for each element and access their values.
I appreciate the suggestions given, but I actually tried an alternative solution. Instead of referring to the elements by name or id, I refer to them by class and by name. I use the class (variable) to do the toggle function and the name (which is a one dimensional array) to get their values.
In short, this is the general idea of the code:
The checkbox declaration
echo '<td><input type="checkbox" class="'.$x.'" name="check_list[]" value="1"> <br/>';
The toggle function:
function toggle(source, id) {
checkboxes = document.getElementsByClassName(id);
for(var i=0, n=checkboxes.length;i<n;i++) {checkboxes[i].checked = source.checked;}
}
The php code to get the values:
$i=0; $unclean[180];
foreach($_POST['check_list'] as $value){
$unclean[$i] = $value; $i= $i + 1;
}
Then, knowing the dimensions the matrix had, i simply separate this one dimensional array into an array of one dimensional arrays (basically a matrix) iterating through it with a for loop
How would I do that?
According to PHP.net,
$a = "hi";
$hi = 2;
$$a; // returns 2
However, I need:
$i = 2;
$_POST['link$i']; // I need this to return the same thing as $_POST['link2']
Here is how I have my code.
for ($i = 1; $i <= 40; $i++)
{
if(!empty($link$i))
{
$link$i = mysql_real_escape_string($_POST['link$i']);
mysql_query("
INSERT INTO links (link, rimageid) VALUES
('".$link$i."', '".$id."') ");
} else { }
}
The reason I'm doing this is because I have a lot of text input fields posting their values to this file, and I'd like to define and insert each of their values via a for loop instead of manually inserting each single link into mysql.
Right now, I get:
Parse error: syntax error, unexpected T_VARIABLE, expecting ')' in C:\xampp\htdocs\new2.php on line 22
How would I go about doing this?
Thanks!
For array index concatenation, ok, but this code
for ($i = 1; $i <= 40; $i++)
{
if(!empty($link$i))
{
$link$i = mysql_real_escape_string($_POST['link$i']);
mysql_query("
INSERT INTO links (link, rimageid) VALUES
('".$link$i."', '".$id."') ");
} else { }
}
won't work as you expect, i.e. name a variable like the result it's not necessary, why would you want to do that? PHP doesn't care about the variable name and if it's coordinated with the result.
Just do:
for ($i = 1; $i <= 40; $i++)
{
if(!empty($_POST['link'.$i]))
{
$regular_variable_name = mysql_real_escape_string($_POST['link'.$i]);
mysql_query("INSERT INTO links (link, rimageid) VALUES ('".$regular_variable_name."', '".$id."') ");
} else { }
}
How about string concatenation?
$_POST['link'.$i];
You are receiving a syntax error because $link$i is not valid.
if you want the end value to be link2 then you need a solution like Nick Shepherd suggested.
It could be easier to see what is going on if you create the string that you want for the key first.
$key = 'link' . $i;
After that you can use the key whenever you want, in a conditional like
if (!empty($_POST[$key])) {
and again in your mysql_escape
mysql_real_escape_string($_POST[$key]);
$_POST['link' . $i];
This should solve your problem. For indexes of an array you can simply concatenate the string for the index that you are trying to resolve.
yep... you can do the following
$ = 2;
$link = "link" . $i;
if(isset($_POST[$link])){
//do something
}
or
$_POST[$link.$i]
the same goes for methods
$type = "Something";
$method = "get" . $type;
$this->$method(); //calls method -> getSomething()
I'm a rookie with php arrays, and have a problem. I downloaded a blackjack PHP script, it stores the current players hand, deck, and dealers hand in THE $_POST, which isn't good.
So I'm trying to alter it to store them in a database instead. I'm getting errors and this is the code I'm playing with. The original code for drawing a random card from the deck is this:
shuffle($deck);
for ($i = 0; $i < 2; $i++) {
$hand[] = array_shift($deck);
$dealer[] = array_shift($deck);
}
$handstr = serialize($hand);
$deckstr= serialize($deck);
$dealerstr= serialize($dealer);
This works, but what I want to do is only draw a random card if theres no data in the database already. If the user draws, someone could just refresh the page to get a different hand. I want to do something like this:
if ($rs5[hand] == "") {
shuffle($deck);
for ($i = 0; $i < 2; $i++) {
$hand[] = array_shift($deck);
$dealer[] = array_shift($deck);
}
$handstr = serialize($hand);
$deckstr= serialize($deck);
$dealerstr= serialize($dealer);
} else {
$dealer = $rs5[dealer];
$hand = $rs5[hand];
$deck = $rs5[deck];
}
Im getting errors with this, I don't know what I'm doing with arrays really, can anyone point me in the right direction?
I'm not terribly sure what you're trying to do, but for starters:
$dealer = $rs5[dealer];
$hand = $rs5[hand];
$deck = $rs5[deck];
Should probably be:
$dealer = $rs5[$dealer];
$hand = $rs5[$hand];
$deck = $rs5[$deck];
Note the dollar signs on the index variables.
You could do:
if (empty($hand))
or:
if (count($hand) == 0)