Trying to make dynamic option form - php

OK I try this for days and I can't do it so I try to take it step by step first I need to get the info from the database correctly and show it in a form here is the database
CategoryID | CategoryName | ParentID
----------------------------------------
1 | FirstMenuCat1 | 0
2 | FirstMenuCat2 | 0
3 | SubMenuCat1 | 1
4 | SubMenuCat2 | 1
5 | SubMenuCat3 | 2
and here is my last attemp that worked so I know I get the correct data from database but I don't know how to make it a form:
<?php
require_once ('mysqli_connect.php');
$q = "SELECT CategoryName FROM menus where ParentID = '0' ORDER by CategoryID";
$r = #mysqli_query ($dbc, $q) or die("Error: ".mysqli_error($dbc));
/* associative array */
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
printf ("%s\n", $row["CategoryName"]);
}
?>
Here is my attempt to make it but its not working
/* associative array */
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
foreach($row){
echo "<option value=\"". urlencode( $_ ) ."\" $selected >$_</option>\n";
$selected = ""; // only the first element will be marked as selected
}
}
?>
Any ideas?

By looking at option tag i think you are trying to create a combobox list. If it is then First of all do not use \n. The options in a combobox list already shown line by line.
Secondly you have not printed the select tag. Without it the list will not be rendered properly. Try the following code:
echo "<select name='mylist'>";
$selected = "selected";
while (($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) !== FALSE){
echo "<option value='". $row['key']."' $selected >".$row['value']."</option>";
$selected = ""; // only the first element will be marked as selected
}
echo "</select>";
hopefully it may help.

Check this
echo '<select name="" id="">';
/* associative array */
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
// Check the $_ correctly
foreach($row){
echo "<option value='". urlencode( $_ ) ."'>$_</option>\n";
}
}
echo '</select>';
Note*: First element by default will be selected for the dd.

Not sure but I think this is what you need
$optionString = '';
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
{
$value = urlencode($row['CategoryName']);
$optionString .= "<option value='{$value}'>{$row['CategoryName']}</option>";
}
echo "<select>$optionString</select>";

$selected = 'selected';
$htmlSelect = '<select name="elementName" id="elementId">';
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)){
$htmlSelect .= '<option value="' . urlencode( $_ ) . '" ' . $selected . ' >' . $_ . '</option>';
$selected = ""; // only the first element will be marked as selected
}
$htmlSelect .= '</select>';
echo $htmlSelect;
Note 1: It's better to use double quote " instead of single quote ' on element attributes. Some browsers don't like single quotes.
Note 2: Couldn't understand why you're using foreach again in the while statement.
Note 3: If you will not remember which option was selected there is not any need to specify which element is selected, first one will be selected by default.

Related

PHP drop down selection

I've set up a php form that registers a project to our database, it has a drop down that populates from our customer/supplier databases.
I've also set up a function to edit these projects, the problem I have is that when I go to my edit page it just displays the customer/supplier name and not in the drop down but a value box - is there a way to have the edit page display the dropdown but also be selected on the original supplier/customer?
Register project page
<?php
$result = mysql_query('SELECT name FROM customers ORDER BY name ASC');
echo '<select name='client'>';
while($row = mysql_fetch_assoc($result))
{ `
echo '<option value = ''.$row[name].''>'.$row[name].'</option>';
}`
echo '</select>';
?>
Edit page
<input type='text' name='client' value='<?php echo $client; ?>'/>
I tried a few tutorials and code tweaks but kept getting errors. I am aware of my sql injection problem, at the moment this site is internal.
Any help would be appreciated.
thanks
instead of $row[name] you should use $row['name']
$client= "<select name='client'>"; // you had error here also.
while($row = mysql_fetch_assoc($result))
{
$client.= "<option value = '".$row['name']."'>'".$row['name'].'</option>';
}
$client.= '</select>';
now echo $client to get dropdown.no need of constructing separate select tag now.
for selected use like this:
$client1= "<select name='client'>";
while($row = mysql_fetch_assoc($result))
{
if($row['name'] == $clientValue){
$client.= "<option selected='selected' value = '".$row['name']."'>'".$row['name'].'</option>';
}else{
$client1.= "<option value = '".$row['name']."'>'".$row['name'].'</option>';
}
}
$client1.= '</select>';
on echo of $client1 you will get selected based on the value $clientValue which you have to pass.
On your edit page:
<?php
$result = mysql_query('SELECT name FROM customers ORDER BY name ASC');
echo "<select name=\"customer\">";
while($row = mysql_fetch_assoc($result))
{
if ($row['name'] == $client)
{
echo "<option selected value=\"" . $row['name'] . "\">" . $row['name'] . "</option>";
}
else
{
echo "<option value=\"" . $row['name'] . "\">" . $row['name'] . "</option>";
}
}
echo "</select>";
?>
I also suggest that you change the old extension for mysql. I can't see no SQL Injection problem for now, but you should take care of it even if it is internal, because, from different reasons you will forget to sanitize it later. If you are writing it, then write it correctly.
Now for the problem, you are not using the quotes correctly, hence the errors. Do not use the same type of quotes, but change them, like so:
echo '<select name="client">';
Or if you use double quotes for concatenation, use single inside.
In case you have to use the same, escape them with \
For starters, you have a syntax error here:
echo '<select name='client'>';
(There are probably more quoting errors throughout the code, but I digress...)
As for using a drop-down, what you're looking for is the selected attribute. When you're building the page elements to display the form on the "edit" page, presumably you have the values that you're looking to display. When your loop finds an element which matches the value, select it:
while($row = mysql_fetch_assoc($result))
{
if ($knownValue == $row[name]) {
echo '<option selected value = ''.$row["name"].''>'.$row["name"].'</option>';
} else {
echo '<option value = ''.$row["name"].''>'.$row["name"].'</option>';
}
}

PHP HTML select box selected from MYSQL

A simple code that inserts a list of teams in select box.
I would like to set SELECTED team with a id , that is in HREF
http://localhost/teams.php?id=7&years=2011&cups=8
<?php
$query = "select distinct t.team_id,t.team from teams t,years y,cups c where t.team_id=c.team_id and y.year_id=$_GET[years] and c.cup_id=$_GET[cups] ORDER BY t.team ASC";
$res = mysql_query($query);
$option = '';
while($row = mysql_fetch_assoc($res))
{
$option .= '<option value = "'.$row['team_id'].'">'.$row['team'].'</option>';
}
?>
<form>
<select id="tteam" name="team">
<?php echo $option; ?>
</select>
</form>
The problem is that I set team_id=$_GET[id], it shows only one team.
I want the team=7 to be selected, but others still be showing in select box
1st of all, NEVER EVER insert raw data into an SQL query. You are asking for SQL injections.
Secondly, you're missing quotes around your $_GET variables, for example, in your SQL query, you currently access id by using $_GET[id]. This won't work, encapsulate id in quotes, like $_GET['id'].
Thirdly, ESCAPE your data!!
mysql_* functions are now deprecated. You shouldn't be using them in new code. Instead, look into PDO or MySQLi functionality. Also look into prepared queries.
This should be your code:
<?php
$years = mysql_real_escape_string($_GET['years']);
$cups = mysql_real_escape_string($_GET['cups']);
$query = "SELECT distinct t.team_id, vt.team
FROM teams t,years y,cups c
WHERE t.team_id = c.team_id
AND y.year_id = '{$years}'
AND c.cup_id = '{$cups}'
ORDER BY t.team ASC";
$res = mysql_query($query);
$option = '';
while($row = mysql_fetch_assoc($res))
{
// The line below specifies whether the option should be selected.
$selected = $row['team_id']==$_GET['id'] ? 'selected="selected"' : '';
$option .= '<option ' . $selected . ' value= "' . $row['team_id'] . '">' . $row['team'] . '</option>';
}
?>
<form>
<select id="tteam" name="team">
<?php echo $option; ?>
</select>
</form>
Please be aware that you're vulnerable to SQL injections. See: How can I prevent SQL injection in PHP?
With that said, you need to use a conditional statement that compares $row["team_id"] with $_GET["ID"].
while($row = mysql_fetch_assoc($res))
{
if($row["team_id"] == $_GET["ID"])
$option .= '<option value = "'.$row['team_id'].'" selected="selected">'.$row['team'].'</option>';
else
$option .= '<option value = "'.$row['team_id'].'">'.$row['team'].'</option>';
}
while($row = mysql_fetch_assoc($res))
{
$option .= '<option value = "'.$row['team_id'].'" '.($row['team'] == 7 ? 'selected="selected"': '').'>'.$row['team'].'</option>';
}
Compare your id from $_GET with $row['team_id'].
while($row = mysql_fetch_assoc($res))
{
if($row['team_id'] == $_GET["id"])
$option .= '<option value = "'.$row['team_id'].'" selected="selected">'.$row['team'].'</option>';
else
$option .= '<option value = "'.$row['team_id'].'">'.$row['team'].'</option>';
}
I'll just focus on the loop part:
while($row = mysql_fetch_assoc($res))
{
$selected = (isset($_GET['team_id']) && $row['team_id'] == $_GET['team_id']) ? 'selected' : '';
$option .= '<option value = "'.$row['team_id'].'" selected="'. $selected .'">'.$row['team'].'</option>';
}

Mysql to array not working

Hey Everyone i got a little problem! I know its something simple but for some reason i can not figure it out (arrays are kicking my butt!)
I want the results to display like the following...
title 1 | title 2 | title 3 | title 4 |
Title 5 | title 6 | title 7 | title 8 |
But for some reason when the code runs it shows as the following...
t | i |
It spells out the title 1 and not the whole word for each cell of the table.
What am i doing wrong?
$result = mysqli_query($con,"SELECT title FROM donuts");
$rows = 2;
$cols = ceil(count($result)/$rows);
$row = mysqli_fetch_array($result);
echo $result=$row['title'];
echo "<table border='1'>";
$i=0;
for($tr=1;$tr<=$rows;$tr++) {
echo "<tr>";
for($td=1;$td<=$cols;$td++) {
if (isset($result[$i])) {
echo "<td>".$result[$i]."</td>"; $i++;
}
}
echo "</tr>";
}
echo "</table>";
Note the table has no limit on how many columns there are just rows.
Link to working example http://lakeside.donavonscreativeinnovations.com/
You have to loop through the results. Something like this:
// $numrows = mysqli_num_rows($result); // Count rows if you want to know
while( $row = mysqli_fetch_array($result, MYSQLI_ASSOC) ) { // Loop through rows
echo "<tr>";
foreach($row as $key => $value) { // Loop through columns
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
At the moment you loop through each character of a column.
You might want to try it like this:
$result = mysqli_query($con, "SELECT title FROM donuts");
echo '<table>';
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo '<tr>';
foreach ($row as $cell)
{
echo '<td>' . $cell . '</td>';
}
echo '</tr>';
}
echo '</table>';
Here is your problem:
echo $result=$row['title'];
and then you loop through this with the code:
$i=0; for($tr=1;$tr<=$rows;$tr++)
{ echo "<tr>";
for($td=1;$td<=$cols;$td++)
{
if (isset($result[$i])) {
**echo "<td>".$result[$i]."</td>"; $i++;**
Thus you loop through a string outputting each character in that string.

querying database with array variable [duplicate]

This question already has answers here:
create dropdown menu on each loop assign database value to option element
(2 answers)
Closed 9 years ago.
Im working on a page for a sports team where the coach can select his team. What im trying to do is:
1) Print different positions
2) Assign next to position name, players who are ONLY relevant to the
position. (i.e if the positions name is flanker only flankers should
be displayed in the drop-down menu)
My logic for the above problem is:
Assign position names to array called $position Loop over array
querying database, with position having a different value after each loop.
Selected players that match the position gets assigned to an
array called $playerName
Print the $position variable
Create dropdown menu for each position
assign value
from $playername array to the option element in the drop down
menu.
Now there should be different positions with dropdown menus,
next to them, containing player names relevant to position.
//create position array
$position = array(
"THP",
"HKR",
"LH",
"LK4",
"LK5",
"FLH"
);
echo '<form name="slectPlayers" method="post">';
foreach ($position as $pposition) {
$result = mysql_query("SELECT `player_id`,`name`,`surname` FROM `player_info` WHERE `position` = '$pposition'") or die(mysql_error());
while ($row = mysql_fetch_array($result)) { //create arrays
$id[] = $row['player_id'];
$playerName[] = $row['name'];
$playerLastName[] = $row['surname'];
// print position and open select element
foreach ($position as $playerPosition) {
print $playerPosition;
echo '<select>';
foreach ($playerName as $name) { //assign playername to position element
echo '<option>' . $name;
'</option>';
echo '</select>';
echo '<br />';
} //close assign player nae to position loop
} //end print position and open select loop
} //end while loop
} //end opening for each loop
echo '</form>';
unfortunately for me either my logic is wrong or my code is incorrect. This is the ouput I get: (Note only the name Tendai is displayed in all dropdown meus no other names appear)
If been struggling with this one all morning if someone could point me in the right direction it would be greatly appreciated
(note to modirators the picure above does not contain real names and is only a fictional database)
You can do it like this. the logic is something different
function get_players_by_position($position)
{
$query = "SELECT
`player_id`,
`name`,
`surname`
FROM `player_info`
WHERE `position` = $position
ORDER BY name ";
$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = $row;
}
return $data;
}
foreach($position as $pposition){
$data = get_players_by_position($pposition);
echo $pposition;
echo '<select>';
foreach($data as $row){
echo '<option '.$row['id'].'>' . $row['name'].'</option>';
}
echo '</select>';
echo '<br />';
unset($data);
}
In your original code, you could remove the two foreach loops in the while loop. Use $pposition in place of $playerPosition and your code should work as expected. Here's your code, with my suggested changes, in your procedural style:
$position = array(
"THP",
"HKR",
"LH",
"LK4",
"LK5",
"FLH"
);
echo '<form name="selectPlayers" method="post">';
foreach ($position as $pposition) {
$result = mysql_query("SELECT `player_id`,`name`,`surname` FROM `player_info`
WHERE `position` = '$pposition'") or die(mysql_error());
echo '<select name="'. $pposition . '">';
while ($row = mysql_fetch_array($result)) {
print $pposition;
echo '<option value="' . $row['player_id'] . '">'.
$row['name'] .' '. $row['surname'].
'</option>';
} //end while loop
echo '</select>';
echo '<br />';
} //end opening for each loop
echo '</form>';

PHP: using SQL result in a loop without re-executing query

I am trying to add 3 combo boxes which all display the exact same information that comes from my MySQL db. It seems like the code I wrote makes the entire page wait until all 3 combo boxes are populated, before continuing.
<?
$query = "Select * from tblWriters order by surname";
for ($i = 1; $i <= 3; $i++) {
$result = mysql_query($query);
echo "<tr><td>Writer".$i." *</td><td>";
echo "<select name='txtWriter".$i."' style='width: 200px;'>";
echo "<option value ='' selected='selected'></option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value ='" . $row['id'] . "'> " . $row['surname'] . ", " . $row['name'] . "</option>";
}
echo "</select><td></tr>";
}
?>
I would like to optimize this piece of code, so the query will not be executed 3 times, as I believe this is where the page slows down.
If I put
$result = mysql_query($query);
outside of the for loop, the 2nd and 3rd combo box do not populate. I tried looking into resetting the pointer of the result, but I can't seem to figure out how that works.
Also, is there a way I can reuse the while loop, so I don't have to execute it 3 times?
Can someone point me in the right direction?
I'm pretty new to PHP and trying to learn on my own. Any help would be much appreciated. Thanks!
If you move your mysql_query() out of the loop again, you can reset your mysql-result-pointer by using mysql_data_seek() at the beginning or end of your loop.
This will result in:
mysql_query($query);
for($i=1;$i<=3;$i++);
{
mysql_data_seek(0); // reset datapointer
// output querydata
}
I'm obliged however to point out that the mysql-extension is deprecated by now and you should use mysqli or pdo for new projects and code.
Cache the query result in an array, then generate your markup:
$query = "Select * from tblWriters order by surname";
$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_array($result))
{
$data[] = $row;
}
for ($i = 1; $i <= 3; $i++) {
echo "<tr><td>Writer".$i." *</td><td>";
echo "<select name='txtWriter".$i."' style='width: 200px;'>";
echo "<option value ='' selected='selected'></option>";
foreach ($data as $row) {
echo "<option value ='" . $row['id'] . "'> " . $row['surname'] .
", " . $row['name'] . "</option>";
}
echo "</select><td></tr>";
}

Categories