Trouble pre-populating drop down and textarea from MySQL Database - php

I am able to successfully pre-populate my questions using the following code: First Name: <input type="text" name="first_name" size="30" maxlength="20" value="' . $row[2] . '" /><br />
However, when I try to do the same for a drop down box and a textarea box, nothing is pre-populated from the database, even though there is actual content in the database. This is the code I'm using for the drop down and textarea, respectively:
<?php
echo '
<form action ="edit_contact.php" method="post">
<div class="contactfirstcolumn">
Prefix:
<select name = "prefix" value="' . $row[0] . '" />
<option value="blank">--</option>
<option value="Dr">Dr.</option>
<option value="Mr">Mr.</option>
<option value="Mrs">Mrs.</option>
<option value="Ms">Ms.</option>
</select><br />';
?>
AND
Contact Description:<textarea id = "contactdesc" name="contactdesc" rows="3" cols="50" value="' . $row[20] . '" /></textarea><br /><br />
It's important to note that I am not receiving any errors. The form loads fine, however without the data for the drop down and textarea fields.
Thanks!
Tony

Select doesn't work that way.
If you want to pre populate select, you can try this way:
$predata = array(
'blank' => '--',
'Dr' => 'Dr.',
'Mr' => 'Mr.',
'Mrs' => 'Mrs.',
'Ms' => 'Ms.',
);
echo "<select name='prefix'>";
foreach($predata as $value => $label){
echo "<option value='$value' ".($value == $row[0] ? 'selected="selected"' : '').">$label</option>";
}
echo "</select>";

Related

How can I set the default value for an HTML <select> element if I don't know it?

I currently display all the row of my table as form, so the information can directly be modify. Event thought it's a form, all the data are pre-filled in the value field of my input. There is one exeption, a parameter of my form which is not an input but a select. No matter what "Fiscalité IS" is dislay witch correspond the the option value 1.
I try to solve the problem by adding a selected field who take the categories of my table's row as parameter like this:
<select name="categorie" id="cat-select" selected="<?php echo $rows['categorie']; ?>">
I know that I'm supposed to use selected in the option, it's just to show my research. The tricky thing, I don't know in advance witch one should be select. It's depend on a the data in my table, and it's variable in each turn of my loop.
Here is my complete form in my code:
<?php
while ($rows = $result-> fetch_assoc()) {
?>
<div class="data-in-form">
<?php
echo $rows['id'] . " <br> " . " <br> ";
?>
<input type=hidden name="rowid" value="<?php echo $rows['id']; ?>">
<p>nom:</p>
<input type="text" name="nom" minLength="9" maxLength="15" value="<?php echo $rows['nom'];?>">
<p>catégorie:</p>
<select name="categorie" id="cat-select" selected="<?php echo $rows['categorie']; ?>">
<option value="1">Fiscalité IS</option>
<option value="2">Réorganisations, acquisitions et méthodologie</option>
<option value="3">Contrôle et contentieux fiscal</option>
<option value="4">Fiscalité patrimoniale</option>
<option value="5">Fiscalité Immobilière</option>
<option value="6">Introduction à la TVA et droits de douanes</option>
<option value="7">Excel</option>
</select>
<p>url:</p>
<input type="tel" name="url" minLength="3" maxLength="15" value="<?php echo $rows['url'];?>">
<p>img:</p>
<input type="tel" name="img" minLength="9" maxLength="15" value="<?php echo $rows['img'];?>">
<br><br>
<button class="submit-update" id="<?php echo $rows['id']; ?>" >Modifier</button>
<button class="submit-delete" id="<?php echo $rows['id']; ?>" onclick ="deletedata(this.id)">Supprimer</button>
</div>
<?php
}
?>
Here are the fiel of my table:
| id | nom | categorie | url | direct_redirect | img
If $rows['categorie'] contains a number from 1 to 7 you can do this with your select:
<?php
$rows['categorie'] = 6;
$options = [1 => "Fiscalité IS",
2 => "Réorganisations, acquisitions et méthodologie",
3 => "Contrôle et contentieux fiscal",
4 => "Fiscalité patrimoniale",
5 => "Fiscalité Immobilière",
6 => "Introduction à la TVA et droits de douanes",
7 => "Excel"];
echo '<select name="categorie" id="cat-select">';
foreach ($options as $optionNo => $optionText) {
echo '<option value="' . $optionNo . '"';
if ($optionNo == $rows['categorie']) {
echo ' selected';
}
echo '>' . $optionText . '</option>';
}
echo '</select>';
?>
See: https://3v4l.org/8qdYJ
If your site has multiple selects this code could be turned into a function.

Pre-populating and compare select field with 'selected' option

I am pulling form data from home.php into results.php and using $_GET['xxxxx'] to pre-populate fields of another form. I can populate input fields okay, but how would you compare an option field and $sale_type to selected if equal?
home.php
<form action="results.php" method="GET">
<input id="address" name="address" type="text" class="form-control1"/>
<select type="text" name="sale_type" placeholder="Sale Type">
<option value="Sale">For Sale</option>
<option value="Rent">To Rent</option>
</select>
<input name="submit" type="SUBMIT" value="Next" class="form-control1">
</form>
results.php
Option fields are already populated to ensure the form will work if it's used without results from home.php. I need to compare $sale_type value with the option of name="sale_type and if equal change that option value to selected.
$address = $_GET['address'];
$sale_type = $_GET['sale_type']; ?>
<form method="POST">
<input id="address" name="address" type="text" value='<?php echo $address; ?>'>
<select type="text" name="sale_type" placeholder="Sale Type">
<option value="Sale">For Sale</option>
<option value="Rent">To Rent</option>
</select>
<button type="submit" id="filter">Search</button>
<input type="hidden" name="action" value="ek_search">
</form>
What I'd like results to do
$address = $_GET['address'];
$sale_type = $_GET['sale_type']; ?> //If value is Sale
<form method="POST">
<input id="address" name="address" type="text" value='<?php echo $address; ?>'>
<select type="text" name="sale_type" placeholder="Sale Type">
<option value="Sale" selected>For Sale</option> //Change to selected if equal
<option value="Rent">To Rent</option>
</select>
<button type="submit" id="filter">Search</button>
<input type="hidden" name="action" value="ek_search">
</form>
You could check and then marked as selected when condition satisfy. One of the example is :
<option value="Sale" <?php if(condition) echo "selected" ?> >For Sale</option>
You'd compare the variable to value in the option tag like so:
<option value="Sale" <?= ($sale_type === 'Sale') ? 'selected' : ''; ?>>For Sale</option>
Another, option, if you will, is to set an array of sale_types. Instead of checking each individual option value, you could loop through the options and check there. Like this:
$sale_types = [
'Sale' => 'For Sale',
'Rent' => 'To Rent',
'SomeOtherType' => 'Something Else'
];
Then in select element:
<? foreach ($sale_types as $sale_value => $sale_option): ?>
<option value="<?= $sale_option; ?>" <?= ($sale_type === $sale_option) ? 'selected' : ''; ?>><?= $sale_value; ?></option>
<? endforeach; ?>
If you're going to do very much of this at all, my recommendation is to build a PHP function. Otherwise, you end up with a bunch of mixed HTML / PHP to check conditions.
This allows you to set up and display a dropdown quickly any time you need to.
Something like this would do what you want and would be re-usable:
// Function to generate the HTML for a select
function dropdown_array( $name, $value, $array, $placeholder = '' ) {
$temp_input = '<select name="' . $name . '"';
$temp_input .= ( $placeholder ) ? ' placeholder="' . $placeholder . '"' : '';
$temp_input .= '>' . PHP_EOL;
if ( is_array( $array ) ) {
foreach ( $array as $val => $text ) {
$temp_input .= '<option value="' . $val . '"';
if ( $value === $val ) {
$temp_input .= ' selected';
}
$temp_input .= '>' . $text . '</option>' . PHP_EOL;
}
}
$temp_input .= '</select>' . PHP_EOL;
return $temp_input;
}
Then, in your situation, usage would look like so:
$array = array( 'Sale' => 'For Sale', 'Rent' => 'To Rent' );
echo dropdown_array( 'sale_type', $sale_type, $array, 'Sale Type' );

Drop down list in php only working as a default checkbox

I am trying to convert my search page from using a checkbox styled method to being able to use a drop down box to select each separate title header as a potential search option. However when converting this the title drop down box still acts as its old checkbox style, being that it only shows the data that is stored within the title name no matter which title is selected.
PHP Section:
mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}. Error: " . mysql_error());
// Set up our error check and result check array
$error = array();
$results = array();
// First check if a form was submitted.
// Since this is a search we will use $_GET
if (isset($_GET['search'])) {
$searchTerms = trim($_GET['search']);
$searchTerms = strip_tags($searchTerms); // remove any html/javascript.
if (strlen($searchTerms) < 3) {
$error[] = "Search terms must be longer than 3 characters.";
}else {
$searchTermDB = mysql_real_escape_string($searchTerms); // prevent sql injection.
}
// If there are no errors, lets get the search going.
if (count($error) < 1) {
$searchSQL = "SELECT sid, sbody, stitle, sdescription FROM simple_search WHERE ";
// grab the search types.
$types = array();
$types[] = isset($_GET['body'])?"`sbody` LIKE '%{$searchTermDB}%'":'';
$types[] = isset($_GET['title'])?"`stitle` LIKE '%{$searchTermDB}%'":'';
$types[] = isset($_GET['desc'])?"`sdescription` LIKE '%{$searchTermDB}%'":'';
$types = array_filter($types, "removeEmpty"); // removes any item that was empty (not checked)
if (count($types) < 1)
$types[] = "`sbody` LIKE '%{$searchTermDB}%'"; // use the body as a default search if none are checked
$andOr = isset($_GET['matchall'])?'AND':'OR';
$searchSQL .= implode(" {$andOr} ", $types) . " ORDER BY `stitle`"; // order by title.
$searchResult = mysql_query($searchSQL) or trigger_error("There was an error.<br/>" . mysql_error() . "<br />SQL Was: {$searchSQL}");
if (mysql_num_rows($searchResult) < 1) {
$error[] = "The search term provided {$searchTerms} yielded no results.";
}else {
$results = array(); // the result array
$i = 1;
while ($row = mysql_fetch_assoc($searchResult)) {
$results[] = "{$i}: {$row['stitle']}<br />{$row['sdescription']}<br />{$row['sbody']}<br /><br />";
$i++;
}
}
}
}
function removeEmpty($var) {
return (!empty($var));
HTML Section:
<body>
<?php echo (count($error) > 0)?"The following had errors:<br /><span id=\"error\">" . implode("<br />", $error) . "</span><br /><br />":""; ?>
<form method="GET" action="<?php echo $_SERVER['PHP_SELF'];?>" name="searchForm">
Search For: <input type="text" name="search" value="<?php echo isset($searchTerms)?htmlspecialchars($searchTerms):''; ?>" /><br />
Search In:<br />
Body: <input type="checkbox" name="body" value="on" <?php echo isset($_GET['body'])?"checked":''; ?> /> |
Title: <form action="form_action.asp">
<select name="title">
<option value="Test Simple Search 1">Test Simple Search</option>
<option value="Searching Made Easy 101">Search Made Easy</option>
<option value="Gateway to Information">Gateway to Information</option>
<option value="The Gaming World as we Know it">Gaming World</option>
<option value="Hundreds of Ants Attacking">Ants Attacking</option>
<?php echo isset($_GET['title'])?"checked":''; ?> </select> |
Description: <input type="checkbox" name="desc" value="on" <?php echo isset($_GET['desc'])?"checked":''; ?> /><br />
Match All Selected Fields? <input type="checkbox" name="matchall" value="on" <?php echo isset($_GET['matchall'])?"checked":''; ?><br /><br />
<input type="submit" name="submit" value="Search!" />
</form>
<?php echo (count($results) > 0)?"Your search term: {$searchTerms} returned:<br /><br />" . implode("", $results):""; ?>
The option values that are used are the name as the titles stored within stitle within the mysql database. Have I simply implemented them wrong or is my php used after title completely incorrect?
Any advice on what I can do or any code snippets from yourselves would be very appreciated.
Ok I think I get your issue.
First if you want to select more than one item in a dropdown, then you need to add the multiple attribute to the select tag like this <select name="title" multiple>
Now when the user holds the CTRL key down and clicks entries, each clicked entry gets selected.
Secondly the data identifying the selected items will now be returned as an array in $_GET['title'] so if the first 2 options are selected the $_GET['title'] array would look something like this :-
0 - "Test Simple Search 1"
1 - "Searching Made Easy 101"
Now in order to re-select the items that were selected by the user when they submitted the form you have to set the selected="selected" attribute on each of the <option> tags that equate to the selected rows of the dropdown so they look selected when the user sees the form again.
<?php
function was_i_selected($selected_options, $value) {
if ( in_array($value, $selected_options, true) ) {
return 'selected="selected"';
} else {
return NULL;
}
}
?>
<select name="title" multiple>
<option <?php echo was_i_selected($_GET['title'], 'Test Simple Search 1');?> value="Test Simple Search 1">Test Simple Search</option>
<option <?php echo was_i_selected($_GET['title'], 'Searching Made Easy 101');?> value="Searching Made Easy 101">Search Made Easy</option>
<option <?php echo was_i_selected($_GET['title'], 'Gateway to Information');?> value="Gateway to Information">Gateway to Information</option>
<option <?php echo was_i_selected($_GET['title'], 'The Gaming World as we Know it');?> value="The Gaming World as we Know it">Gaming World</option>
<option <?php echo was_i_selected($_GET['title'], 'Hundreds of Ants Attacking');?> value="Hundreds of Ants Attacking">Ants Attacking</option>
</select>
Now that look very clumsy and we have not checked that $_GET['title'] actually exists, so I would probably do it like this :-
<?php
$options = array(
'Test Simple Search 1' => 'Test Simple Search',
'Searching Made Easy 101' => 'Search Made Easy',
'The Gaming World as we Know it' => 'Gaming World',
'Hundreds of Ants Attacking' => 'Ants Attacking'
);
<select name="title" multiple>
<?php
foreach ( $options as $val => $label ) {
if ( ! empty($_GET['title'] ) {
$sel = in_array($val, $_GET['title'], true) ? 'selected="selected"' : '';
echo '<option ' . $sel . ' value="' . $val . '">' . $label . '</option>';
} else {
echo '<option value="' . $val . '">' . $label . '</option>';
}
}
?>
</select>

List Box Should be Drop down

to every one
I have some values in my data base i Want to display them with check boxes.
those values should be display when i click at the button. This should not in combo box.
because I want to post multiple values at one time.
Please help with thanks
<?php
$womenlist=mysql_query("select * from tbl_cycleduraion where user_id=$_SESSION[user_id]");
$gs=0;
while($girlslist=mysql_fetch_array($womenlist))
{
$gs++;
?>
<li style="background-color:#CCC; width:150px;"><label for="chk1"><input type="checkbox" name="chk_<?php echo $gs?>" id="chk<?php echo $gs?>" value="<?php echo $girlslist['calName'];?>" <?php if($_REQUEST['chk_'.$gs]==$girlslist['calName']){?> checked="checked"<?php }?>><?php echo $girlslist['calName']." ".$girlslist['calDesc']; ?> </label></li>
<?php }?>
You could limit the number of columns in your query (not SELECT * ...). You've put the <input> inside the <label>. The <label>'s for="" attribute is hardcoded as chk1. You could take out the inline style="" on the <li> and put it into a stylesheet. I've "tidied" it up a bit (untested):
$womenlist = mysql_query("select * from tbl_cycleduraion where user_id=$_SESSION[user_id]");
$gs = 0;
while( $girlslist = mysql_fetch_array($womenlist) )
{
$gs++;
echo '<li style="background-color:#CCC; width:150px;">'
. '<label for="chk' . $gs . '">' . $girlslist['calName'] . ' ' . $girlslist['calDesc'] . '</label>'
. '<input type="checkbox" name="chk_' . $gs . '" id="chk' . $gs . '" value="' . $girlslist['calName'] . '"
. (($_REQUEST['chk_'.$gs]==$girlslist['calName']) ? 'checked="checked"' : '') . '></li>';
}
Not sure entirely what you're asking for here (as it looks like you already have this working with checkboxes), but you can in fact post multiple values with a select box. You just use the multiple attribute, and specify the name as an array with the square brackets:
<form action="yourscript.php" method="post">
<select name="women[]" multiple="multiple">
<option value="woman1_name">Woman 1</option>
<option value="woman2_name">Woman 2</option>
<option value="woman3_name">Woman 3</option>
</select>
<input type="submit" />
</form>
If you post a form with this, selecting woman 2 & 3, var_dump($_POST); yields:
array(1) {
["women"]=>
array(2) {
[0]=>
string(11) "woman2_name"
[1]=>
string(11) "woman3_name"
}
}
Alternatively, if you want the values of your checkboxes to come through in a similar fashion, change them so they all have the same name, but with the square brackets on the end. This HTML would yield similar POST data:
<input type="checkbox" name="women[]" value="Woman 1" />
<input type="checkbox" name="women[]" value="Woman 2" />
<input type="checkbox" name="women[]" value="Woman 3" />
So, to create a dropdown using this, here's an adaptation of your code. I believe this is what you're after:
<?php
$options = '';
$womenlist=mysql_query("select * from tbl_cycleduraion where user_id=$_SESSION[user_id]");
while($woman=mysql_fetch_array($womenlist)) {
$options .= '<option value="'.$woman['calName'].'"'.((!empty($_REQUEST) && in_array($woman['calName'],$_REQUEST['women'])) ? ' selected="selected"' : '').'>'.$woman['calName'].' '.$woman['calDesc'].'</option>';
}
?>
<label for="women">Women:</label>
<select id="women" name="women[]" multiple="multiple">
<?php echo $options; ?>
</select>

How to make form elements "remember" selection?

I am using php to build a "change classifieds" page right now.
I use Mysql as a db.
Currently I use PHP to fetch all mysql information about the classified, and then I output it like this:
$table.="
<select name='year' id='year'>
<option id='2000' value='2000'>2000</option>
<option id='2001' value='2001'>2001</option>
<option id='2002' value='2002'>2002</option>
</select>";
echo $table;
I have a picture upload tool which submits the page to itself, and at the same time uploads the picture, and shows it at the bottom of the page. The problem is, whenever this is done, the user must fill in all information again, because they are "forgotten".
I know about input type="text" where you simply can do something like this:
<input type="text" name="text" value="<?php echo $_POST['text'];?>">
but what about selects? Radios? etc?
What should I do here?
Thanks
You can set the selected attribute to "selected" to make it the default/current selection:
<option id="2000" value="2000" selected="selected">2000</option>
php example:
$options = array( '2000' => '2000', '2001' => '2001', '2002' => '2002' );
$selected = '2001';
$select = '<select name="year" id="year">';
foreach ( $options as $key => $value )
{
$select .= ' <option value="' . $key . ( $key == $selected ? '" selected="selected">' : '">' ) . $value . '</option>';
}
$select .= '</select>';
<option
id='2000'
value='2000'
<?php if(isset($year) && $year === '2000') echo 'selected="selected"'?>
>2000</option>
Where $year contains the year from wherever. This assumes $year is a string. If $year is an integer change the condition to:
if(isset($year) && $year === 2000)
For radio buttons and checkboxes just replace selected="selected" with checked="checked".
For selects, it is a bit more intense you need to loop through the data and check if the value equals the selected value (at least that is the easiest to do). But you could apply a similar technique as seen with the checkbox / radio.
<input type="radio" name="radio1" value="1" <?php echo (!empty($_POST['radio1']))?'checked':''?>>
<input type="checkbox" name="chkbox1" value="1" <?php echo (!empty($_POST['chkbox1']))?'checked':''?>>
Since you are creating the table PHP side here is the code:
$years = array('2000', '2001', '2002');
$table .= "<select name='year' id='year'>";
foreach ($years as $year) {
$table .= "<option id='" . $year . "' value='" . $year . "' " .
(($_POST['year'] == $year)?'selected':'') . ">" . $year . "</option>\n";
}
$table.="</select>";
Should get you on the right track for select statements. The ? and : make up the ternary operator which is a shortened if / else statement.
You can conditionnally echo selected in PHP, depending on the value to select.
<?php
$selected[$_GET['year']] = "selected='selected'";
$table.="
<select name='year' id='year'>
<option id='2000' value='2000' " . $selected['2000'] . ">2000</option>
<option id='2001' value='2001' " . $selected['2001'] . ">2001</option>
<option id='2002' value='2002' " . $selected['2002'] . ">2002</option>
</select>";
echo $table;
?>

Categories