How to set checkboxes to checked in loop? - php

I wonder how I can make sure a checkbox is checked on a postback if for example someone leaves the addressfield blank it should then make sure the user doesn't have to refill the whole form again. In this case I'm generating 31 checkboxes. It's really frustrating.
$output_checkbox = '';
$checked = '';
for ($i=1; $i <= 31; $i++) {
if (isset($_POST['dagen'])) {
foreach ($_POST['dagen'] as $dag) {
if ($dag == $i) {
$checked . $i = 'checked';
}
}
}
$output_checkbox .= '<input type="checkbox" name="dagen[]" value="' . $i . '" id="day_' . $i . '"' . $checked . ' /><label for="day_' . $i . '">Dag ' . $i . '</label>';
}
Here is the form but there isn't the problem:
<form action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post">
<div>
<label for="email">Email:</label>
<input id="email" type="text" name="email" value="<?php if(isset($_POST['email'])) { echo $_POST['email'];} ?>" />
</div>
<div>
<label for="month">Maand:</label>
<select id="month" name="month">
<?php echo $output; ?>
</select>
</div>
<div>
Dagen:
<?php echo $output_checkbox; ?>
</div>
<input type="submit" name="btnSend" value="Verzenden" />
</form>
Here is an example of how I normally do it but it's a lot easier since it comes out of a database:
$output = '';
while ($row = $result->fetch_array(MYSQLI_BOTH)) {
$selected = '';
if (isset($_POST['month']) && $_POST['month'] == $row['id']) {
$selected = 'selected';
}
$output .= '<option value="' . $row['id'] . '"' . $selected . '>' . $row['naam'] . '</option>';
}

Something like this:
$output_checkbox = '';
for ($i=1; $i <= 31; $i++) {
if (isset($_POST['dagen'])) {
foreach ($_POST['dagen'] as $dag) {
if ($dag == $i) {
$checked = 'checked';
}
else{
$checked = '';
}
$output_checkbox .= '<input type="checkbox" name="dagen[]" value="' . $i . '" id="day_' . $i . '"' . $checked . ' /><label for="day_' . $i . '">Dag ' . $i . '</label>';
}
}
}

Related

Adding variables to database with a for loop

My main question is why is PDO::exec not executing every iteration of my loop, and instead only executing in the first iteration.
I am trying to insert coordinates into my MySQL database.
My database structure is (number(primary key), x, y, z).
I ask the user to insert a number ($n), and then ask them to fill in $n sets of coordinates.
The users inputs are passed to another page with $_POST, then retrieved by dynamic variable names and inserted into the database.
Everything works, except the loop only writes to the database its first iteration. So I end up with results for x1,z1,y1 but nothing else.
Can anyone explain what I am doing wrong (other than not using arrays)?
<?php
require_once('db.php');
$n = $_POST['selectOption'];
for($i = 1; $i < $n+1;$i++){
${'x' . $i} = $_POST["x" . $i];
${'y' . $i} = $_POST["y" . $i];
${'z' . $i} = $_POST["z" . $i];
$rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
VALUES ('$n', '${'x' . $i}', '${'y' . $i}', '${'z' . $i}')");
}
?>
Here is my form
<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
?>
x<?php echo $i+1;?> <input name="x<?php echo $i+1;?>" type=text>, y<?php echo $i+1;?> <input name="y<?php echo $i+1;?>" type=text>, z<?php echo $i+1;?> <input name="z<?php echo $i+1;?>" type=text><br>
<?php
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" oonClick="document.location.href='aaron_stockdale_dynamic_process.php'" value="Submit">
</form>
require_once('aaron_stockdale_database.php');
$n = $_POST['selectOption'];
for($i = 1; $i < $n+1;$i++){
$x = $_POST["x" . $i];
$y = $_POST["y" . $i];
$z = $_POST["z" . $i];
$rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
VALUES ('$n', '$x', '$y', '$z')");
}
the rest is on you ;)
And also check if any of the fields a primary key, that will prevent insert it twice.
Since you have received an acceptable answer for your question, I'd like to give you a hint on your html code.
<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
?>
x<?php echo $i+1;?> <input name="x<?php echo $i+1;?>" type=text>, y<?php echo $i+1;?> <input name="y<?php echo $i+1;?>" type=text>, z<?php echo $i+1;?> <input name="z<?php echo $i+1;?>" type=text><br>
<?php
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" oonClick="document.location.href='aaron_stockdale_dynamic_process.php'" value="Submit">
</form>
Now, this code can be cleaned up a bit.
<form action="aaron_stockdale_dynamic_process.php" method="post" name="coordinateForm">
<?php
for($i = 0; $i < $n; $i++)
{
echo 'x' . $i+1 . '<input name="x' . $i+1 . '" type=text>, y' . $i+1 . ' <input name="y' . $i+1. '" type=text>, z' . $i+1 . '<input name="z' . $i+1 . '" type=text><br>'
}
?>
<br>
<input type="hidden" name="selectOption" value="<?php echo $n;?>">
<input type="submit" value="Submit">
</form>
I changed the "oonClick" to "onClick", and then afterwards I removed it, as when you submit, you don't need to navigate, as the browser will do this, upon submission.
And then I removed the repetitive opening and closing of php tags, and combined all the echos into one.
Here's my solution in one file:
<!DOCTYPE html>
<html lang=en>
<head>
<script>
function validcoord(e) {
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();
// control keys
if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
return true;
// Numeral Characters
else if ((("0123456789-.,").indexOf(keychar) > -1))
return true;
else
return false;
}
</script>
<style>
input[type="number"] { text-align: right; width: 50px; }
label { margin-left: 4em; }
</style>
</head>
<body>
<?php
define ("SELF", $_SERVER['PHP_SELF']);
define ("EOL", "\r\n");
// Modify as needed
define ("MINNUMCORDS" , "1");
define ("MAXNUMCORDS" , "10");
define ("DFLTNUMCORDS", "2");
$formSubmitted = (empty($_POST)) ? FALSE : TRUE;
if (!$formSubmitted) {
$htmlOutput = '
<form action="' . SELF . '" method=post name=foo id=foo>
<input type=hidden name=current value=0>
<label>Enter the number of Coordinates:
<input type=number autofocus onFocus="this.select()"' .
' min=' . MINNUMCORDS .
' max=' . MAXNUMCORDS .
' value=' . DFLTNUMCORDS .
' name=numcords /></label>
</form>' . EOL;
echo $htmlOutput;
} // end if not submitted
else { // a form HAS been submitted
foreach ($_POST as $key => $value) { $$key = $value; }
unset($_POST);
if (!empty($coord)) { // We got some input that may be a valid x,y,z coordinate
if ( substr_count($coord, ",") != 2 ) {
$error = "We're looking for THREE numbers seperated by TWO commas.";
} // end if we don't have three values
else { // We got three Values
$coord = trim($coord);
list($x,$y,$z) = explode(",", $coord);
if ( !(is_numeric($x) && is_numeric($y) && is_numeric($z)) ) {
$error = "We're looking for three VALID NUMBERS seperated by two commas.";
} // end if all three numbers are not valid
else { // We got three Values and each of them are numbers
require('db.php');
$rowsAffected = $db->exec("INSERT INTO coordinate3d (number,x,y,z)
VALUES ('$numcords', '$x', '$y', '$z')");
//echo "INSERT INTO coordinate3d (number,x,y,z) VALUES ('$numcords', '$x', '$y', '$z')<br />" . EOL;
} // end three valid numbers
} // end three values
} // end if we have some input in $coord
if ($error) {
echo "~~ " . $error . "<br /><br />" . EOL;
--$current;
} // end if error
if ( $current < $numcords ) {
$htmlOutput = 'Please enter the coordinate in the form: x,y,z (Ex: -.4,2,8.5)' . EOL;
$htmlOutput .= '<form action="' . SELF . '" method=post name=bar id=bar>' . EOL;
$htmlOutput .= ' <input type=hidden name=numcords value="' . $numcords . '" />' . EOL;
$htmlOutput .= ' <input type=hidden name=current value="' . ++$current . '" />' . EOL;
$htmlOutput .= ' <label>Coord #' . $current . ': ';
$htmlOutput .= '<input type=text name=coord size=12 maxlength=48 ' .
'autofocus onKeyPress="return validcoord(event);" /></label>' . EOL;
$htmlOutput .= '</form>' . EOL;
echo $htmlOutput;
} // end if we need to get another coord
} // end form was submitted
?>
</body>
</html>

pagination on php limit 50

Can anyone help me with the pagination? I am trying this code on pagination and the pages are showing but when clicked on the pages like Next or the number with links it gives a syntax error.
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?page=2' at line 1"
My tables data is around 250 and I wanted to limit it to 50 data per page.
Here is my code: (pagination section - is the problem)
<link rel="stylesheet" type="text/css" href="css/navbar.css">
<?php include 'navbar.php';?>
<br>
<?php
if(!isset($_GET['table'])){
echo 'You must assign a table to view.';
exit;
}
session_start();
//Connect here
$conn = mysqli_connect("localhost", "root", "", "dkusers");
$table = mysqli_real_escape_string($conn, $_GET['table']);
$fields = array();
$q = mysqli_query($conn, "SHOW COLUMNS FROM " . $table) or die(mysqli_error($conn));
while($r = mysqli_fetch_assoc($q)) $fields[count($fields)] = $r['Field'];
echo '<b><font size="4">Table: </b>', $table, '</font><br>';
// -----------------INSERT-----------------
if(isset($_POST['action']) && $_POST['action'] == "Insert"){
if(!isset($_POST['insert'])){
echo '<h3>Insert Row</h3>';
echo '<form method="post"><input type="hidden" name="action" value="' . $_POST['action'] . '" />';
echo '<table border="1" cellpadding="7"><tr><th>Field</th><th>Value</th><th>MD5</th></tr>';
foreach($fields as $key => $value){
echo '<tr><td>' . $value . ':</td><td><input type="text" name="field_' . $value . '" /></td><td><input type="checkbox" name="md5_' . $value . '" /></td></tr>';
}
echo '<tr><td><input type="submit" name="insert" value="Submit" /></td><td colspan="2">Back</td></tr></table></form>';
exit;
}else{
$first = true;
$query = "INSERT INTO " . $table;
foreach($_POST as $key => $value){
if(strrpos($key, "field_", -strlen($key)) !== false){
$key = substr($key, 6);
$query .= sprintf("%s%s", ($first) ? " (" : ",", $key);
$first = false;
}
}
$query .= ") VALUES";
$first = true;
foreach($_POST as $key => $value){
if(strrpos($key, "field_", -strlen($key)) !== false){
$key = substr($key, 6);
$query .= sprintf("%s'%s'", ($first) ? " (" : ",", (isset($_POST['md5_' . $key])) ? md5($value) : $value);
$first = false;
}
}
$q = mysqli_query($conn, $query . ")");
if($q) echo 'Successfully inserted row into table!<br/><br/>'; else echo mysqli_error($conn) . '<br/><br/>';
}
}
// -----------------DELETE-----------------
if(isset($_POST['action']) && $_POST['action'] == "Delete"){
if(!isset($_POST['rows'])){
echo 'You didn\'t send any rows to delete.<br/><br/>';
}else{
$count = 0;
for($i = 0;$i < count($_POST['rows']);$i++){
if($_POST['rows'][$i] >= count($_SESSION['store'])) continue;
$query = "DELETE FROM " . $table . "";
$row = $_SESSION['store'][$_POST['rows'][$i]];
$first = true;
foreach($row as $key => $value){
$query .= sprintf(" %s %s = '%s'", ($first) ? "WHERE" : "AND", $key, $value);
$first = false;
}
$q = mysqli_query($conn, $query . " LIMIT 1");
if(!$q) echo mysqli_error($conn) . '<br/>';
$count += mysqli_affected_rows($conn);
}
echo 'Successfully deleted ' . $count . ' row(s)!<br/><br/>';
}
}
// -----------------MODIFY-----------------
if(isset($_POST['action']) && $_POST['action'] == "Modify"){
if(!isset($_POST['rows'])){
echo 'You didn\'t send any rows to modify.<br/><br/>';
}else if(isset($_POST['modify'])){
$count = 0;
for($i = 0;$i < count($_POST['rows']);$i++){
if($_POST['rows'][$i] >= count($_SESSION['store'])) continue;
$first = true;
$query = "UPDATE " . $table . " SET";
foreach($_POST as $key => $value){
if(strrpos($key, "field_", -strlen($key)) !== false){
$key = explode("_", $key, 3);
if($key[1] == $i){
$query .= sprintf(((!$first) ? "," : "") . " %s = '%s'", $key[2], (isset($_POST['md5_' . $key[1] . '_' . $key[2]])) ? md5($value) : $value);
$first = false;
}
}
}
$row = $_SESSION['store'][$_POST['rows'][$i]];
$first = true;
foreach($row as $key => $value){
$query .= sprintf(" %s %s = '%s'", ($first) ? "WHERE" : "AND", $key, $value);
$first = false;
}
$q = mysqli_query($conn, $query . " LIMIT 1");
if(!$q) echo mysqli_error($conn) . '<br/>';
$count += mysqli_affected_rows($conn);
}
echo 'Successfully updated ' . $count . ' row(s)!<br/><br/>';
}else{
echo '<h3>Modify Row</h3>';
echo '<form method="post"><input type="hidden" name="action" value="' . $_POST['action'] . '" />';
for($i = 0;$i < count($_POST['rows']);$i++) if($_POST['rows'][$i] < count($_SESSION['store'])) echo '<input type="hidden" name="rows[]" value="' . $_POST['rows'][$i] . '" />';
echo '<table border="1" cellpadding="7"><tr><th>Field</th><th>Value</th><th>MD5</th></tr>';
for($i = 0;$i < count($_POST['rows']);$i++){
if($_POST['rows'][$i] >= count($_SESSION['store'])) continue;
if($i != 0) echo '<tr><td colspan="3"><hr/></td></tr>';
$row = $_SESSION['store'][$_POST['rows'][$i]];
foreach($row as $key => $value){
echo '<tr><td>' . $key . ':</td><td><input type="text" name="field_' . $i . '_' . $key . '" value="' . $value . '" /></td><td><input type="checkbox" name="md5_' . $i . '_' . $key . '" /></td></tr>';
}
}
echo '<tr><td><input type="submit" name="modify" value="Submit" /></td><td colspan="2">Back</td></tr></table></form>';
exit;
}
}
// -----------------SEARCH-----------------
echo '<br><form method="post">Search: <input type="text" name="filter" value="' . ((isset($_POST['filter'])) ? $_POST['filter'] : '') . '"/><br/>Filter by: <br/>';
for($i = 0;$i < count($fields);$i++) echo '<input type="checkbox" name="' . $fields[$i] . '"' . ((isset($_POST['filter']) && isset($_POST[$fields[$i]])) ? ' checked' : '') . '/>' . $fields[$i] . ' ';
echo '</form><form method="post"><table border="1" cellpadding="7"><tr>';
for($i = 0;$i < count($fields);$i++) echo '<th>' . $fields[$i] . '</th>';
echo '<th>-</th></tr>';
$sql = "SELECT * FROM " . $table;
if(isset($_POST['filter'])){
$filter = mysqli_real_escape_string($conn, $_POST['filter']);
foreach($fields as $key => $value) if(!isset($_POST[$fields[$key]])) unset($fields[$key]);
if(count($fields) > 0){
$first = true;
foreach($fields as $key => $value){
$sql .= " " . (($first) ? "WHERE" : "OR") . " " . $value . " LIKE '%" . $filter . "%'";
$first = false;
}
}
}
// -----------------Bottoms (Above table)-----------------
echo '<input type="submit" name="action" value="Modify" /> <input onclick="return confirm(\'Are you sure you want to delete these rows?\')" type="submit" name="action" value="Delete" /> <input type="submit" name="action" value="Insert" /><br><br></form>';
$_SESSION['store'] = array();
$q = mysqli_query($conn, $sql) or die(mysqli_error($conn));
while($r = mysqli_fetch_assoc($q)){
echo '<tr>';
foreach($r as $key => $value) echo '<td>' . $value. '</td>';
echo '<td><input type="checkbox" name="rows[]" value="' . count($_SESSION['store']) . '" /></td></tr>';
$_SESSION['store'][count($_SESSION['store'])] = $r;
}
// -----------------Bottoms (Below table)-----------------
echo '</table>';
//echo '<br><input type="submit" name="action" value="Modify" /> <input onclick="return confirm(\'Are you sure you want to delete these rows?\')" type="submit" name="action" value="Delete" /> <input type="submit" name="action" value="Insert" /></form>';
?>
<br>
// -----------------Pagination-----------------
<br>
<?php
$start=0;
$limit=50;
if(isset($_GET['page']))
{
$page=$_GET['page'];
$start=($page-1)*$limit;
}
else{
$page=1;
}
//Fetch from database first 10 items which is its limit. For that when page open you can see first 10 items.
$query=mysqli_query($conn,"select * from $table LIMIT $start, $limit");
?>
<?php
//print 10 items
while($result=mysqli_fetch_array($query))
{
//echo "<li>".$result['username']."</li>";
}
?>
<?php
//fetch all the data from database.
$rows=mysqli_num_rows(mysqli_query($conn,"select * from $table"));
//calculate total page number for the given table in the database
$total=ceil($rows/$limit);
if($page>1)
{
//Go to previous page to show previous 10 items. If its in page 1 then it is inactive
echo 'PREVIOUS';
}
if($page!=$total)
{
////Go to previous page to show next 10 items.
echo 'NEXT';
}
?>
<?php
//show all the page link with page number. When click on these numbers go to particular page.
for($i=1;$i<=$total;$i++)
{
if($i==$page) { echo "<li class='current'>".$i."</li>"; }
else { echo '<li>'.$i.'</li>'; }
}
?>
You have error on html URL syntax
echo 'NEXT';
The correct would be
echo 'NEXT';
You have to use ? only for the first URL parameter, & for the following, if any.

checkboxes only appearing for first and last options

What the code does below is it retrieves individual options in a full option type. So for example if $option is A-D, then by using the explode, it will be able to display each individual option to output A B C D.
Now In this example I want A B C D to each have it's own checkbox. But with the code below it is just creating checkbox for A and D, the first and last options when it should do it for A, B, C, D. How can this be done?
function ExpandOptionType($option) {
$options = explode('-', $option);
foreach($options as $indivOption) {
echo '<p><input type="checkbox" name="options[]" id="option-' . $indivOption . '" value="' . $indivOption . '" /><label for="option-' . $indivOption . '">' . $indivOption . '</label></p>';
}
if(count($options) > 1) {
$start = array_shift($options);
$end = array_shift($options);
do {
$options[] = $start;
}while(++$start <= $end);
}
else{
$options = explode(' or ', $option);
}
return implode(" ", $options);
}
function ExpandOptionType($option) {
$options = explode('-', $option);
if(count($options) > 1) {
$start = array_shift($options);
$end = array_shift($options);
do {
$options[] = $start;
}while(++$start <= $end);
}
else{
$options = explode(' or ', $option);
}
foreach($options as $indivOption) {
echo '<p><input type="checkbox" name="options[]" id="option-' . $indivOption . '" value="' . $indivOption . '" /><label for="option-' . $indivOption . '">' . $indivOption . '</label></p>';
}
return implode(" ", $options);
}
This way you first change the options array and then create the checkboxes.
Well, I am not quite sure what the if-else in your function does, but is this what you are thinking about?
<?php foreach (range('A','D') as $letter): ?>
<p>
<input type="checkbox" name="options[]" id="option-<?php echo $letter ?>" value="<?php echo $letter ?>" />
<label for="option-<?php echo $letter ?>"><?php echo $letter ?></label>
</p>
<?php endforeach ?>
Or, in a function:
function ExpandOptionType($from, $to) {
$output = '';
$range = range($from, $to);
foreach ($range as $letter) {
$output .= '<p>';
$output .= "<input type=\"checkbox\" name=\"options[]\" id=\"option-{$letter}\" value=\"{$letter}\" />";
$output .= "<label for=\"option-{$letter}\">{$letter}</label>";
$output .= '</p>';
}
return $output;
}
echo ExpandOptionType('A', 'D');

Invalid argument supplied for foreach() - Yet output is showing

I am working to show editable fields based on query results. I know the query is functioning properly, and it is returning an array. The array is populating the form fields properly, however, I am getting the "Invalid argument supplied for foreach()" warning. I am new at this, and at a loss as to what is happening. I appreciate any suggestions.
Here is the code:
// Grab the profile data from the database
$query8 = "SELECT * FROM EDUCATION WHERE ID_NUM = '" . $_SESSION['IDNUM'] . "' ORDER BY RECORD";
$data = mysqli_query($dbc, $query8);
echo '<pre>' . print_r($data, true) . '</pre>';
$rowcount = 1;
while ($row = mysqli_fetch_assoc($data))
{
if (is_array($row))
{
echo '<p> It is an Array</p>';
}
foreach($row as &$item)
{
$record = $row['RECORD'];
$school = $row['SCHOOL'];
$type = $row['TYPE'];
$degree = $row['DEGREE'];
$major = $row['MAJOR'];
$grad = $row['GRAD'];
?>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<legend>Education History </legend>
<?php
echo '<input type="hidden" id="record" name="record" value="' . $record . '">';
echo 'Rowcount' . $rowcount. '</br>';
// Insert Listbox here
$queryschool = "SELECT * FROM SCHOOL";
$list = mysqli_query($dbc, $queryschool);
if($list)
{
echo 'School Type? ';
echo '<select name="school_code">';
while($row = mysqli_fetch_assoc($list))
{
echo "<option value={$row['CODE']}>{$row['TYPE']}" ;
echo '</option>';
}
echo '</select>';
}
echo '<br />';
echo '<label for="school">School Name:</label>';
echo '<input type="text" id="school" name="school" size="40" maxlength="40" value="' . ( (!empty($school)) ? $school : "") . '" /><br />';
// Insert Listbox here
$querydegree = "SELECT * FROM DEGREE";
$list = mysqli_query($dbc, $querydegree);
if($list)
{
echo 'Degree Type? ';
echo '<select name="degree_code">';
while($row = mysqli_fetch_assoc($list))
{
echo "<option value={$row['CODE']}>{$row['DEGREE']}";
echo '</option>';
}
echo '</select>';
}
echo '<br />';
echo '<label for="major">Field of study:</label>';
echo '<input type="text" id="major" name="major" size="40" maxlength="40" value="' . ( (!empty($major)) ? $major : "") . '" /><br />';
echo '<label for="grad">Did you graduate?:</label>';
echo '<input type="radio" id="grad" name="grad" value="Y" ' . ($grad == "Y" ? 'checked="checked"':'') . '/>Yes ';
echo '<input type="radio" id="grad" name="grad" value="N" ' . ($grad == "N" ? 'checked="checked"':'') . '/>No<br />';
?>
</fieldset>
<?php
$rowcount++;
}
}
;
echo '<label for="another">Do you need to enter more educational experience?:</label>';
echo '<input type="radio" id="another" name="another" value="Y" ' . ($another == "Y" ? 'checked="checked"':'') . '/>Yes ';
echo '<input type="radio" id="another" name="another" value="N" ' . ($another == "N" ? 'checked="checked"':'') . '/>No<br />';
?>
<input type="submit" value="Save Profile" name="submit" />
</form>
foreach ($row as &$item)
replace this with:
foreach ($row as $item)
And then for each variable you should probably change
$record = $row['RECORD'];
to
$record = $item['RECORD'];
foreach($row as &$item) should be
foreach($row as $item)
there is no need to use the foreach here you can just do this like like
while ($row = mysqli_fetch_assoc($data))
{
$record = $row['RECORD'];
$school = $row['SCHOOL'];
$type = $row['TYPE'];
$degree = $row['DEGREE'];
$major = $row['MAJOR'];
$grad = $row['GRAD'];
}
You're not changing the row item, so don't pass by reference to the foreach. Also, shouldn't you be using $item instead of $row? Do this:
foreach($row as $item)
{
$record = $item['RECORD'];
$school = $item['SCHOOL'];
....
Don't do This:
foreach($row as &$item)
{
$record = $row['RECORD'];
$school = $row['SCHOOL'];
....

PHP for each drop down selected

I got this piece of code here...
<form action="InvoiceNotice.php?action=invoicenotice" method="post">
<label for="fordays">Select Day</label>
<select name="daySelected" id="daySelected">
<option value="0">Today</option>
<?php
$array = array_combine(range(1,$InvoiceDaysArray['days']), range(1,$InvoiceDaysArray['days']));
foreach($array as $row => $value){
$selected = '';
$daySelected = 0;
if($daySelected == $row){
$selected = 'SELECTED';
}
echo "<option selected='" . $selected . "' value='" . $row . "'>" . $value . " days ago</option>";
}
?>
</select>
<input type="submit" name="button" id="button" value="Submit" />
</form>
My issue is with the $selected the $daysSelected variable comes from what has been selected. What I am trying to do is when a user selects an option, that option is now selected in the dropdown and the page returns, after the client hits submit.
Does any one know what I am talking about?
Thanks
I would do something like:
foreach($array as $row => $value){
$selected = '';
if($_POST['daySelected'] == $row){
$selected = ' selected="selected"';
}
echo "<option" . $selected . " value='" . $row . "'>" . $value . " days ago</option>";
}
Although you probably only need selected instead of selected="selected".
I see some problems in your code:
first you are setting $daySelected = 0; and then try compare with variable from database, day 0 is not in your foreach loop try this
<form action="InvoiceNotice.php?action=invoicenotice" method="post">
<label for="fordays">Select Day</label>
<select name="daySelected" id="daySelected">
<option value="0">Today</option>
<?php
$array = array_combine(range(1,$InvoiceDaysArray['days']), range(1,$InvoiceDaysArray['days']));
foreach($array as $row => $value){
$selected = '';
$daySelected = $_POST['daySelected'];
if($daySelected == $row){
$selected = "selected=SELECTED";
}else {$selected='';}
echo "<option '" . $selected . "' value='" . $row . "'>" . $value . " days ago</option>";
}
?>
</select>
<input type="submit" name="button" id="button" value="Submit" />
</form>

Categories