PHP multi directional arrays from a grid - php

I'm creating a crossword page on my site, I produce a grid (form) with 8 x 8 input boxes. when I fill in the answers they are sent to a page to assess them but this is where i have the problems.
the values are sent using form method GET, so if the top line read q,w,e,r,t, , ,y then it would pass this over like this :-
submit.php?0[0]=q&0[1]=w&0[2]=e&0[3]=r&0[4]=t&0[5]=&0[6]=&0[7]=y&1[0]
But when I put the values into an array, the empty values are left out, so when printing out the array it reads as "q,w,e,r,t,y" instead of "q,w,e,r,t, , ,y"
I currently fill the array like this :-
$one = $_GET['0'];
My HTML form is:
<form action='submit.php' method='get' name='xword' id='xword1'> <?php
$array=array(
array("h","e","l","l","o","0","0","0"),
array("e","0","0","0","0","0","0","0"),
array("l","0","0","0","0","0","0","0"),
array("l","0","0","0","0","0","0","0"),
array("o","0","0","0","0","0","0","0"),
array("0","0","0","0","0","0","0","0"),
array("0","0","0","0","0","0","0","0"),
array("0","0","0","0","0","0","0","0"),
);
$X = 0;
while ($X < "8") {
$Y = 0;
while ($Y < "8") {
if ($array[$X][$Y] == "0") {
echo "<input type='text' id='text' name='" . $X . "[$Y]' class='blank'>";
} else {
echo "<input type='text' id='text' name='" . $X . "[$Y]' class='text'>";
}
$Y++;
}
echo "<br />";
$X++;
}
?> <input type='submit' value='Submit'>
Where am I going wrong?

I don't see the empty spaces within the array being left out.
This is the output of print_r($_GET) when I type qwer in the first four text fields and ty in the last two in the first row.
Getting the data with $one = $_GET['0']; works fine (without quotes work too), and when I implode the first row, it outputs exactly what you had expected.
echo implode(', ', $_GET[0]);
OUTPUT: q, w, e, r, , , t, y

Related

I can't get my array checkbox values in PHP

I can't find out why this isn't working so please don't shred me for asking this question although it's been answered. I have a HTML array of checkboxes and I'd like to get the value of what is checked. I'm getting the questions via a cURL request.
I've tried several combinations of changing variable names, adding index values, using the
foreach ($var1 as $var1 => $value)
and still nothing.
PHP to display the questions:
$exquest = curl_exec($ch);
curl_close($ch);
$exquest = json_decode($exquest, true);
$numOfQuests = $exquest["questcount"];
for ($i=0; $i<$numOfQuests; $i++)
{
echo "<input type='checkbox' name='q[]' value='" . $exquest['question$i'] . "'> " . $exquest["question$i"] . "<br /><br />";
}
PHP to collect checked questions:
if(is_array($_POST['q'])){
foreach($_POST['q'] as $value){
print_r($value);
var_dump($value);
}
}
OUTPUT:
The outputs I've gotten thus far are either "Array" repeated the number of times equal to the number of boxes checked, or [0]=> 0, [1] => [1], etc but even then it only goes by total number checked not the sequence (i.e index 0, 2, and 4) it'll always come back 0,1,2 etc.
As #Ryan Vincent suggested, by checking var_dump($_POST); I determined that nothing was being sent from one page to the other aside form the N number of checked boxes."
Solution: I was missing the $i in q[] for name and id. Thanks all!
echo "<input type='checkbox' name='q[$i]' id='q[$i]' value='" . $exquest["question$i"] . "'> " . $exquest["question$i"] . "<br /><br />"

is that anyway for array to didnt back to [0] again and countinue it in last number?

i have an array which have 2 or more value ,
here my php :
for ($c = 0; $c < $jumpack; $c++) {
$packinglist = $_POST['packinglist'][$c];
$a= mysql_query("INSERT INTO packing_list VALUES('','$packinglist','$surat[id_surat]','$surat[no_surat_jalan]')");
}
and here my html :
for($i=1;$i<=5;$i++)
{
echo"
<input class='form-control' type='text' id='jumrow' name='jumpack[]' value=''/>
";
for($i=1;$i<=20;$i++){
<input class='form-control sedang' type='text' id='packinglist_$i' name='packinglist[]'/>
}
}
so i need to loop jumpack[] and i need to loop packinglist[] too
thanks
If i understand correctly you need to know the amount of fields posted?
$jumpacks = count($_POST['jumpack']);
$packinglists = count($_POST['packinglist']);
Now $jumpacks would be 5 and $packinglists would be 20 in your example.
Edit:
(trying to understand what you mean :)
foreach($_POST['jumpack'] as $jumpackvalue) {
//this means we are going over each posted jumpack, there are 5 in your example, so on each run we get the value of the next one in $jumpackvalue.
echo $jumpackvalue.'<br>'; //to test
//you can do the same now with the packinglist inside this loop
foreach($_POST['packinglist'] as $listvalue) {
echo $listvalue.'<br>'; //to test
}
}

PHP Loop Through CSV and Print Selected Row

I'm trying to display a CSV file in a browser and print the selected (via radio button) row.
Here's my code to print the CSV file (with a radio button next to each row):
<?php
echo "<html><body><table border='1'>";
$f = fopen("data.csv", "r");
$row = 1;
echo "<form method='post' action='submit.php'>";
while (($line = fgetcsv($f)) !== false) {
$to_print = implode(",", $line); // added this and changed value below (to use it)
echo "<tr><td><input type='radio' name='env[$row]' value='$to_print' /></td>";
foreach ($line as $cell) {
echo "<td contenteditable='true'>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
++$row;
}
fclose($f);
echo "</table><br><Input type='submit'></form></span></body></html>";
?>
I have a submit button at the bottom that (when clicked) should pass the data in the selected row to submit.php which should print it.
Here's the submit.php:
<?php
echo "<html><body>";
print_r($_POST); // this prints what I need
if (! empty($_POST['env'])) {
$j=0;
foreach ($_POST['env'] as $env) {
// Can't get anything to print in here
++$j;
}
}
echo "</body></html>";
?>
But it prints nothing. I'm guessing it has something to do with the 'value' of my radio button:
value='<?php echo $line;?>]'
That can't be right...
Any suggestions would be great. Thanks!
The problem with your code is this line:
echo "<tr><td><input type='radio' name='env[<?php echo $row;?>]'
You are echoing some HTML from within PHP. Inside the line your are echoing out, you are opening <?php tags again. Debugging what is being POSTed, you are actually just sending the string "<?php echo $row;?>"
To fix this issue, change your echo line to this:
echo "<tr><td><input type='radio' name='env[$row]' ...
As long as you are using double quotes, the $row variable will be interpreted and you'll get the outcome that you want.
Edit:
Once you have the data output to the page correctly, you need to reconsider how you are looping over the data.
The value of $line is set by [fgetcsv](http://php.net/manual/en/function.fgetcsv.php) which returns an array. You are setting this array as the value to the input like this: value=$line, but seeing as $line is an array, PHP is making an array-to-string conversion, and you're not getting what you expect.
Solution: Either pick a single index of the array to set as value (such as $value=$line[0]) or output the td within the inner loop, where you are looping over each field within the row.

Getting Parse Error Unexpected "

I am getting an error with the following message :-
Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\xampp\htdocs\game.php on line 12
Here is the source code :-
<?php
$words=$_GET['words'];
$array=explode(",",$words);
$j=count($array)-1;
goto a;
a: shuffle($array);
$num=$array[0];
echo "The Number Is = $num";
echo "<br />";
echo "Please Enter The Number Within 10 Seconds";
echo "<form method=\"get\" action=\"$_SERVER[\'PHP_SELF\']\" "; **<--Line 12**
echo "<input type=\"text\" name=\"num\"";
echo "<input type=\"submit\" value=\"Press Me! \"";
$input=$_GET['num'];
goto b;
b: if($input==$array[0] && $array!=NULL)
{
array_pop($array);
goto a;
}
elseif($array!=NULL)
{
goto a;
}
else
break;
?>
Please don't say about the GOTO but rather on how to fix the error as I am only experimenting with it to see if it would solve the given question.
Change
echo "<form method=\"get\" action=\"$_SERVER[\'PHP_SELF\']\" ";
Into
echo '<form method="get" action="'.$_SERVER['PHP_SELF'].'">';
It's much more simpler for the eyes.
I'll comment on all of it.
First, to fix your syntax error (and the later HTML errors you'll have). The single-quotes in the PHP_SELF substitution don't need escaped, you need to complete your opening tags, and you need to close your form tag.
<?php
$words=$_GET['words'];
$array=explode(",",$words);
$j=count($array)-1;
goto a;
a: shuffle($array);
$num=$array[0];
echo "The Number Is = $num";
echo "<br />";
echo "Please Enter The Number Within 10 Seconds";
echo "<form method=\"get\" action=\"$_SERVER['PHP_SELF']\" >";
echo "<input type=\"text\" name=\"num\" />";
echo "<input type=\"submit\" value=\"Press Me! \" />";
echo "</form>";
$input=$_GET['num'];
goto b;
b: if($input==$array[0] && $array!=NULL)
{
array_pop($array);
goto a;
}
elseif($array!=NULL)
{
goto a;
}
else
break;
Now, to make it not spaghetti code and to simplify your logic:
<?php
$words=$_GET['words'];
$array=explode(",",$words);
while (sizeOf($array) > 0) {
shuffle($array);
$num = $array[0];
echo "The Number Is = $num";
echo "<br />";
echo "Please Enter The Number Within 10 Seconds";
echo "<form method=\"get\" action=\"$_SERVER['PHP_SELF']\" >";
echo "<input type=\"text\" name=\"num\" />";
echo "<input type=\"submit\" value=\"Press Me! \" />";
echo "</form>";
$input = $_GET['num'];
if($input === $array[0]) {
array_pop($array);
}
}
Now it's at least clear what the code does - that is, the form is provided with a comma-delimited list of numbers on the query parameter "words". The list is shuffled, and the user is asked to enter the new "first" item - effectively a random item from the list. When submitted by the user, "num" is passed. If this number is the same as the first in the list, it removes the last number. Either way, as long as the array is non-null, then loops back on itself (effectively ad infinitum, spitting out the same form for each number on the list. I'm not sure this is what you wanted, since you're not handling $_GET[num] as an array.
Assuming you actually get a form, rather than just peg your server, the script then checks if "num" is present and, if so, removes it from the numbers list.
This is where it gets interesting; on submission, the script is started again. "words" is empty, so the form asks the user to enter "". If it wasn't, the list would have been re-randomized, so even if the user dutifully entered what was asked, the script wouldn't recognize it.
This is one of the reasons we don't use GOTO; it obfuscates your code flow. What's clear in a while loop is inscrutable using GOTO.
So what I assume is supposed to be the requirement:
You're presented with a number to enter. You enter it and submit the form. The number is removed from the list, and you're asked to enter another one. Once it's empty, it would be nice if you're told that.
So, to do this in a way that makes sense, let's do this using some OOP.
I know what you're going to say: this appears to be more complex - however, I want you to note that what baking everything into a class does: it encapsulates the stuff you're doing into one place, and separates out each phase of the request into separate functions.
Additionally, comments notwithstanding, it effectively documents nonobvious and repetitive tasks, like getting items off the $_REQUEST (or $_GET) object, or getting an item from an array (if it's an array and if the item exists on it) in a way that is safe and predictable.
Lastly, it's readable. It's a bit of work to look at the contents of the while loop and work out what it does; in this class, you can tell: it checks that the array is not empty and that the submitted number is the same as the requested number; if so, it removes that number.
Additionally, rather than shuffle the list each time, we just pick each one off at random.
<?php
class RandomNumberGame {
private $startCount;
private $numberMax;
private $numbers;
private $index;
/**
Produce an array containing $count random numbers between 0 and $max
*/
public function generateRandoms($count, $max) {
$nums = array();
for ($i = 0; $i < $count; $i += 1) {
$nums[] = rand(0, $max);
}
return $nums;
}
/**
Get an item from an array if it exists; if not, or if the array doesn't exist, return null
*/
public function getIfExists($array, $item) {
if (empty($array)) return null;
if (!array_key_exists($item, $array)) return null;
return $array[$item];
}
/**
returns a random number from the list of numbers
*/
function pickRandomNumber() {
return rand(0, sizeof($this->numbers) - 1);
}
/**
Handle the request data
$request
['nums'] - list of numbers with which to populate $this->numbers
['index'] - the index of the currently-selected number
['num'] - the user's entry
If nums[index] == num, that item is removed and a new index is selected.
*/
public function processRequest($request) {
$nums = $this->getIfExists($request, 'nums');
if (empty($nums)) {
$this->numbers = $this->generateRandoms($this->startCount, $this->numberMax);
} else {
$this->numbers = explode(',', $nums);
}
$this->index = $this->getIfExists($request, 'index');
if (empty($this->index)) {
$this->index = $this->pickRandomNumber();
}
$num = $this->getIfExists($request, 'num');
if (empty($num)) return;
while (!empty($this->numbers) && $this->getCurrentNumber() === $num) {
$this->removeCurrentNumber();
}
}
/**
Removes the entry in $this->numbers pointed to by $this->index, and assigns $this->index a new random position
*/
public function removeCurrentNumber() {
// In $nums, replace 1 items at $index with [] - effectively, remove item $index from $num
array_splice($this->numbers, $this->index, 1, array());
// Pick a new random item
$this->index = $this->pickRandomNumber();
}
/**
Get the currently selected number
*/
public function getCurrentNumber() {
return $this->getIfExists($this->numbers, $this->index);
}
/**
Generate the form for output to the user
If there are no numbers left, provide a congratulation, and a link to start over
*/
public function getForm($endpoint) {
if (sizeof($this->numbers) === 0) {
return "Hey, you're done! Start over.";
}
$nums = join(',', $this->numbers);
return <<<HEREDOC
<form method="post" action="{$endpoint}">
<input type="hidden" name="nums" value="{$nums}" />
<input type="hidden" name="index" value="{$this->index}" />
<label for="num">
The number is {$this->getCurrentNumber()}<br />
Please enter the number within 10 seconds<br />
<input id="num" type="text" name="num" autofocus/>
</label>
<input type="submit" value="Press Me!" />
</form>
<!-- Optional: define some Javascript to disable the form in 10 seconds -->
HEREDOC;
}
public function RandomNumberGame($startCount = 10, $numberMax = 100) {
//Basic initialization
$this->startCount = $startCount;
$this->numberMax = $numberMax;
}
}
//Finally, the program:
$rng = new RandomNumberGame();
$rng->processRequest($_REQUEST);
echo $rng->getForm($_SERVER['PHP_SELF']);
You should wrap server variable with brackets:
echo "<form method=\"get\" action=\"{$_SERVER['PHP_SELF']}\">";
printf ("<form method=\"get\" action=\"{$_SERVER['PHP_SELF']}\" ");
Two errors. You can't escape single quotes in a double quoted string, and when you are working with an array inside a string, you need to surround it with {}.
The answer is you're putting in single quotes for the array of $_SERVER:
echo "<form method=\"get\" action=\"$_SERVER[\'PHP_SELF\']\" ";
simply use
echo "<form method=\"get\" action=\"$_SERVER[PHP_SELF]\" ";
instead. the idea of the '' inside the array is to pass the string. no need to pass it within a quotes.
You're missing closing > in three lines
echo "Please Enter The Number Within 10 Seconds";
echo "<form method=\"get\" action=\"$_SERVER[PHP_SELF]\">";
echo "<input type=\"text\" name=\"num\">";
echo "<input type=\"submit\" value=\"Press Me! \">";
Yours:
echo "<form method=\"get\" action=\"$_SERVER['PHP_SELF']\" ";
^-- here
echo "<input type=\"text\" name=\"num\"";
^-- here
echo "<input type=\"submit\" value=\"Press Me! \"";
^-- here
Plus, [\'PHP_SELF\'] You should not be escaping single quotes.
Use [PHP_SELF] or {$_SERVER['PHP_SELF']} wrapping the variable in curly braces.
Doesnt it need a space before the != and after
From
b: if($input==$array[0] && $array!=NULL)
to this
b: if(($input==$array[0]) && ($array != NULL))
Have wrapped it in extra brackets for good measure too

How can I combine values of checkboxes with values of text in php?

I'm new with PHP, and I'm making a html form which consist basically in two options: First, the client select a series of checkboxes (parts from an equipment) and then write the amounts of each selected checkbox...
<td><input id="11.11.015.0002" name="pecas[]" type="checkbox" value="11.11.015.0002 - BATERIA CHUMBO ACIDO 6V/4AH" /></td>
<td><input name="qntd[]" size="7" type="text" /></td>
and in php:
if(isset($pecas))
{
$mensagem .= "Peças Selecionadas:<br /><br />";
}
else {
echo "<script>alert('Selecione as Peças Desejadas!'); location.href='http://www.lyuz.com.br/pecas/erro';</script>";
exit;
}
foreach ($pecas as $pecas_s) {
} $mensagem .= " - ".$pecas_s."<br />";
That gave me all the selected checkboxes (parts), now I'm trying to get only the input_text (amounts) associate with these selected checkboxes..
I'm stuck. Help.
Specify a key in the name of each element. Use a number and just make sure that pecas[1] corresponds to qntd[1]. Then when you loop over one of the arrays, the keys will be the same in the other array. For example:
<?php
$count = 0;
foreach($itemList as $item){
echo "<tr>\n";
echo " <td><input type='checkbox' id='{$item['id']}' name='pecas[{$count}]'></td>\n";
echo " <td><input type='test' id='{$item['id']}' name='qntd[{$count}]'></td>\n";
echo "</tr>\n";
$count++;
}
If there are 3 checkboxes and quantity boxes, and lets say the 1st and 3rd boxes are checked, but not the 2nd. Your post array will look like:
array(
'pecas'=> array(
0 => 'some value', //notice, no 1 key because the second checkbox was not checked.
2 => 'some other value'
),
'qntd' => array(
0 => 'some qntd',
1 => '' //1 was not checked, so nothing should have been entered in the second textbox.
2 => 'some other qntd'
)
);
The keys 0 (first checkbox) and 2 (third) will exist in the 'pecas' array and will correspond with keys 0 and 2 in the 'qntd' array. You can then loop over the data like:
//check that at least one checkbox was checked
if(!empty($_POST['pecas'])){
//loop over the checkboxes getting key ($k) and value ($v).
foreach($_POST['pecas'] as $k=>$v){
//display a message
echo "Pecas {$v} ({$k}) was checked with a qntd of {$_POST['qntd'][$k]}<br>";
}
}
Change
foreach ($pecas as $pecas_s) {
$mensagem .= " - ".$pecas_s."<br />";
}
to
for($x = 0; $x < count($pecas); ++$x) {
$mensagem .= " - ".$pecas[$x]. ": " . $qntd[$x] . "<br />"; //Example
}
Since it appears that for every $pecas there is a $qntd, so you just need to get the index location of $pecas, and grab that same index location in $qntd
--
Let me add however that checkboxes only get passed IF they are checked, the input boxes will ALWAYS be passed. So you could have a disparity, where the indexes don't align! You might want to use some javascript to disable an input box if its checkbox is not selected.
Well, I manage to solve this with help of #Jonathan Kuhn with a little different approach.
In HTML form, I gave indexes in each element,
<td><input id="11.11.015.0002" name="pecas[1]" type="checkbox" value="11.11.015.0002 - BATERIA CHUMBO ACIDO 6V/4AH" /></td>
<td><input name="qntd[1]" size="7" type="text" /></td>
And in PHP file, I replace
foreach ($pecas as $pecas_s) {
$mensagem .= " - ".$pecas_s."<br />";
}
to
array('pecas'=> array(), 'qntd' => array());
if(!empty($_POST['pecas']))
{
foreach($_POST['pecas'] as $k=>$v)
{
$mensagem .= "- {$v} - QUANT.: {$_POST['qntd'][$k]}<br>";
}
}
And, finally, my mail returns value of each textbox when the checkbox is checked! \o/

Categories