Setting up different options and getting their values - php

I'm using the following code to add various select elements to my page. However, as I'm doing this in a while loop, the value for all the elements is the same
function options($pos, $count) {
for ($i = 0; $i < $count; $i++) {
$options = '';
$STH = //code to get data from db
$STH->execute();
while($row2 = $STH->fetch()) {
$options .="<option>" . $row2['name'] . "</option>";
}
$menu= "<select name='filter' id='filter'>
" . $options . "
</select>";
echo $menu;
}
}
I then need to get the value of each of the select element after the user presses a button. But as the name for each select element is the same I don't know how to do this. Is there any way around this problem?
For eg, If the count is 5, five separate drop down lists will be created (even though the options in each of them are identical). The user then selects the options relevant to him and presses the submit button. I then need to get the values that he chose from the dropdown menus but I can't figure out how to do this as the name for all the dropdown menus is the same

Assuming you have many select tags with dynamic options
Solution is to make your name of select tag different(dynamic)
<form method="POST">
<?php
cust_options(5);
function cust_options($count) {
for ($i = 0; $i < $count; $i++) {
$options = '';
$j = 1;
while($j < 4) {
$options .="<option>" . 'option'.$j . "</option>";
$j++;
}
$ind = $i+1;
$temp = 'filter_'.$ind;
$menu= "<select name='$temp'>
" . $options . "
</select>";
echo $menu;
}
}
?>
<input type="submit">
<?php print_r($_POST); ?>
</form>

You should do something like this :
<select name='filter' id='filter'>
<?php
while($row2 = $STH->fetch()) {
$options .="<option>" . $row2['name'] . "</option>";
} ?>
</select>";

Related

Add "selected" in a <select> based on value from database

how do I select the correct value in a when I get the value from a database on page load?
I have this code now, but when it runs it gives the attribute "selected" to every number after the given number from the database.
<?php
$i = 8;
while ( $i <=24 ) {
if ($i == $store_info['weekdays_open_time']) {
$selected = " selected";
}
print ("<option value='" . $i ."'" . $selected . ">" . $i . "</option>");
$i++;
}
?>
Change you code to:
<?php $i = 8; while ( $i <=24 ) {
$selected = ($i == $store_info['weekdays_open_time'])?" selected" : "";
print ("<option value='" . $i ."'" . $selected . ">" . $i . "</option>");
$i++;
} ?>
You need to reset the $selected variable inside the while loop:
<?php
$i = 8;
while ($i <= 24) {
$selected = '';
if ($i == $store_info['weekdays_open_time]) $selected = ' selected="selected"';
print ("<option value='" . $i ."'" . $selected . ">" . $i . "</option>");
$i++;
}
?>
Edit: Make sure you always set a value for each variable you use; it's a good habit. In your code you used the variable selected inside the print function, without always having a variable value assignment first.
you never clear your $selected variable, basically once it finds a correct answer, $selected is set to " selected" and is no longer an empty variable, so each iteration when you call for it, it prints " selected" not "";
<?php
$i = 8;
while ( $i <=24 ) {
$selected = ( $i == $store_info['weekdays_open_time']) ? " selected='selected'" : "";
print ("<option value='" . $i ."'" . ( () ? )$selected . ">" . $i . "</option>");
$i++;
} ?>
You could just replace the whole if statement :
<?php
$i = 8;
while ( $i <= 24 ) {
echo "<option value='" . $i ."'" ;
echo ($i == $store_info['weekdays_open_time'] ? ' selected' : '');
echo ">" . $i . "</option>";
++$i;
}
Check it :
<?php
$i = 8;
while ($i <= 24) {
?>
<option value="<?PHP echo $i; ?>" <?PHP if ($i == $store_info['weekdays_open_time']) { echo "selected='selected'";} ?> > <?PHP echo $i; ?></option>
<?
$i++;
}
?>
Hope it will definitely work :)
You may simply use
$i = 8;
while ( $i <=24 ) {
$selected = $i == $store_info['weekdays_open_time'] ? 'selected' : '';
echo "<option value='$i' $selected>$i</option>";
$i++;
}
Also, it's not necessary to use . when you have variables inside "double quotes" and it's better to use echo instead of print because echo is a language construct and it's faster than print function.
An Example.

Creating dynamic dropdown lists

I want to create dynamic select lists. For example: I have 5 students in my db. My goal is to create 5 selects ,and in every select all students which are in database. So if user inserts a 6th student in the database, the page should display 6 selects, and in every select names of 6 students.
I've tried with this code, but it only creates 1 select, containing 4 students(the first one from the db is missing).
The Code:
$con=mysqli_connect("localhost","root","","novi-studomat");
$exe="SELECT * FROM kolegij WHERE id_student='$id_student'";
$i=1;
$execute=mysqli_query($con,$exe);
while($result=mysqli_fetch_array($execute))
{
echo '<select name=student'.$i.'>';
echo '<option value="-1" >Choose student</option> <br/>';
while($res=mysqli_fetch_array($execute))
{
echo '<option value='.$res["id_student"].'>'.$res["name"].'</option> <br/>';
}
echo '</select>';
$i++;
}
$con=mysqli_connect("localhost","root","","novi-studomat");
$exe="SELECT * FROM kolegij WHERE id_student='$id_student'";
$i=1;
$execute=mysqli_query($con,$exe);
$select = '';
for($j = 0; $j < mysqli_num_rows($execute); $j++) {
$select .= '<select name=student' . $j . '>';
$select .= '<option value="-1" >Choose student</option> <br/>';
while($result=mysqli_fetch_array($execute)) {
$select .= '<option value=' . $res["id_student"].'>' . $res["name"] . '</option>';
$i++;
}
$select .= '</select>';
}
echo $select;
UPDATE
inside the while
$select = '<select name=student' . $j . '>';
$select .= '<option value=' . $res["id_student"].'>' . $res["name"] .
change this lines by this other
$select = '<select name="student' . $j . '">';
$select .= '<option value="' . $res["id_student"]."'>' . $res["name"] .
we missed the double quotes for value and in select name
Problem solved, I just needed to insert vars $exe and $execute inside for loop, so after every iteration $result is refreshed,otherwise it just prints options in first select...
CODE:
$con=mysqli_connect("localhost","root","","novi-studomat");
$exe="SELECT * FROM kolegij WHERE id_student='$id_student'";
$execute=mysqli_query($con,$exe);
$select = '';
for($j = 0; $j < mysqli_num_rows($execute); $j++)
{
$exe="SELECT * FROM kolegij WHERE id_student='$id_student'";
$execute=mysqli_query($con,$exe);
$select .= '<select name=student' . $j . '>';
$select .= '<option value="-1" >Choose student</option> <br/>';
while($result=mysqli_fetch_array($execute))
{
$select .= '<option value=' . $res["id_student"].'>' . $res["name"] . '</option>';
}
$select .= '</select>';
}
echo $select;

php select multiple checkboxes

i have this code, which helps me to retrieve all table fields and associate a check button to them, but this code is generating the same name, i mean it shows me all the fields, but named the same... id
I need their particulatr name..
can you please see what's wrong?
Thanks..
<form action='report.php' method='post'>
<?php // Script 12.7 - sopping.php
$db = mysql_connect('localhost', 'root', '');
mysql_select_db('db_up', $db);
echo "<table border='1' class='tabtext'>";
$result = mysql_query("SELECT * FROM hostess");
$numrows = mysql_num_rows($result);
$numfields = mysql_num_fields($result);
// show headers
echo '<thead><tr>';
for ($field = 0; $field < $numfields; $field++) {
$field_name = mysql_field_name($result, $field); // instead of $i
echo '<th><label><input type="checkbox" name="checkbox[' . $field_name . ']" value="1"/> ' . $field_name . '</label></th>';
}
echo '</tr></thead>';
echo '<tbody>';
for ($row = 0; $row < $numrows; $row++) {
$data = mysql_fetch_assoc($result);
echo '<tr>';
for ($field = 0; $field < $numfields; $field++) {
$field_name = mysql_field_name($result, $field);
if (isset($_POST['checkbox'][$field_name])) {
echo '<td>' . $data[$field_name] . '</td>';
}
}
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
?>
<input type='submit' value='Submit' />
</form>
The second argument of the mysql_field_name function isn't defined so I am pretty sure PHP is assuming you mean 0 and is returning the first fieldname only. Use the variable you defined ($field) as the index.
Should be:
for ($field = 0; $field < $numfields; $field++) {
$field_name = mysql_field_name($result, $field); // instead of $i
echo '<th><label><input type="checkbox" name="checkbox[' . $field_name . ']" value="1"/> ' . $field_name . '</label></th>';
}
You are using mysql_field_name and it always return the same name for you(for column 0), because $i is not defined.

Need help with incrementing 2 variables in post form

I'm trying to allow a user to edit a row of their data with POST from a displayed form. The query is working and the table properly displays everything except a name value in the form input field. I've tried numerous variations but the name value keeps coming up blank. The problem might be with this line:
echo $field_name;
Here is the code:
<form action="process.php" method="POST">
<?
$qry = "SELECT activity, site, date, FROM home WHERE user_id='$session->user_id' ORDER BY date";
$res = mysql_query($qry);
$field_name = mysql_field_name($res, 0);
function mysql_fetch_all($res) {
while($row=mysql_fetch_array($res)) {
$return[] = $row;
}
return $return;
}
function create_table($dataArr) {
echo "<form action=\"process.php\" method=\"POST\"><table><tr>";
for($j = 0; $j < 3; $j++) {
echo "<td><input type=\"text\" name=\"";
echo $field_name;
echo "\" maxlength=\"30\" value=" .$dataArr[$j]. "></td>";
}
echo "<td><input type=\"hidden\" name=\"subedit\" value=\"1\"><input type=\"submit\" value=\"Update\"></td></tr></table></form>";
}
$all = mysql_fetch_all($res);
echo "<table class='data_table'>";
echo "<tr><td colspan=\"3\"><h2>Current Profile</h2></td></tr>";
echo "<tr><small><td>Activity </td><td>Site </td><td>Date </td></small></tr>";
for($i = 0; $i < count($all); $i++) {
create_table($all[$i]);
}
echo "</table></form>";
$field_name is out of scope (check out PHP's variable scope page). Try changing your create_table function to accept the $field_name var like so:
function create_table($dataArr, $field_name) {
...
}
...
for($i = 0; $i < count($all); $i++) {
create_table($all[$i], $field_name);
}
Or using global (not as recommended)
function create_table($dataArr) {
global $field_name;
...
}
Try this code:
<form action="process.php" method="POST">
<?
$qry = "SELECT activity, site, date, FROM home WHERE user_id='$session->user_id' ORDER BY date";
$res = mysql_query($qry);
$field_name = mysql_field_name($res, 0);
function mysql_fetch_all($res) {
while($row=mysql_fetch_array($res)) {
$return[] = $row;
}
return $return;
}
function create_table($dataArr, $field_name) {
echo "<form action=\"process.php\" method=\"POST\"><table><tr>";
for($j = 0; $j < 3; $j++) {
echo "<td><input type=\"text\" name=\"";
echo $field_name;
echo "\" maxlength=\"30\" value=" .$dataArr[$j]. "></td>";
}
echo "<td><input type=\"hidden\" name=\"subedit\" value=\"1\"><input type=\"submit\" value=\"Update\"></td></tr></table></form>";
}
$all = mysql_fetch_all($res);
echo "<table class='data_table'>";
echo "<tr><td colspan=\"3\"><h2>Current Profile</h2></td></tr>";
echo "<tr><small><td>Activity </td><td>Site </td><td>Date </td></small></tr>";
for($i = 0; $i < count($all); $i++) {
create_table($all[$i], $field_name);
}
echo "</table></form>";
However, I do recommend that you try to create a Table class. It would be much more efficient and neater.

How do I add x-number HTML-formatted items to my page?

I'm trying to use PHP to do this:
<if !empty($list) {echo
.
.
.
?>
And get the result:
Additional options:
<p><input type="checkbox" name="1">1</input></label></p>
<p><input type="checkbox" name="2">2</input></label></p>
.
.
.
<p><input type="checkbox" name="n">n</input></label></p>
</legend>
</fieldset>
Given the context of the question, I am guessing here. But it seems that the you do not understand the checkbox, given that you do not even assign it a value that and this would be a pain to loop through on the form processing end.
Assuming that $list is an array (borrowing some code from Gazler)
$cnt = count($list);
$checkBoxes = "";
for ($i=1; $i<$cnt; $i++) {
$checkBoxes .= '<p><input type="checkbox" name="checkBoxes" value="' . $i . '">' . $i . '</input></label></p>' . PHP_EOL;
}
echo $checkBoxes . '</legend>' . PHP_EOL . '</fieldset>';
Then on your form processing side, it will be easy to loop through the checked boxes like so:
if (isset($_POST['checkBoxes'])) {
foreach ($_POST['checkBoxes'] as $val) {
// $val will contain the value of the selected boxes
}
}
Using this system, it should get you to where you want to be.
Assuming $list is an array
for($i=1; $i<count($list); $i++)
{
echo '<p><input type="checkbox" name="'.$i.'">'.$i.'</input></label></p>'."\n";
}
If not, please provide the contents of $list.
Part 1:
// echo the 3-bar, expanded series (alternating sequence), of the tags array
<legend>Additional Options:</p>
$cnt = count($list);
$checkBoxes = "";
for ($i=1; $i<$cnt; $i++) {
$checkBoxes .= '<p><input type="checkbox" name="checkBoxes" value="' . $i . '">' . $i . '</input></label></p>' . PHP_EOL;
}
echo $checkBoxes . '</legend>' . PHP_EOL . '</fieldset>' . "\n" . </legend>;
Part 2:
// loop through the checkboxes
if (isset($_POST['checkBoxes'])) {
foreach ($_POST['checkBoxes'] as $val) {
// $val will contain the value of the selected boxes
}
}

Categories