Load data from database & retain data between postbacks - php

In PHP Project, I'm creating page a which retrieve the data from database on page load then allow the user to change data & Update. I have to use input text and option controls to display data. Editing form data may involve in few POST requests. To load data from database and retain data between POSTs I use this approach.
Load Data from Database
$oClass = new DataClass();
$oClass ->GetRecordById($_REQUEST['id']);
$dataName = $oClass ->Name;
$dataYear = $oClass ->Year;
INPUT TEXTs
<input type="text" name="txtName" value="<?php echo isset($_POST['txtName']) ? $_POST['txtName'] : $dataName ?>" >
OPTIONs
$arrYears = GetYears();
foreach ($arrYears as $year) {
if (isset($_POST['ddlYear'])) {
if ($_POST['ddlYear'] == $year) {
echo '<option value="' . $year . '" selected="selected">' . $year . '</option>';
} else {
echo '<option value="' . $year . '">' . $year . '</option>';
}
} else {
if ($dataYear == $year) {
echo '<option value="' . $year . '" selected="selected">' . $year . '</option>';
} else {
echo '<option value="' . $year . '">' . $year . '</option>';
}
}
}
Is there a better approach to retain data between posts than using like
if (isset($_POST['NAME']))
{$_POST['NAME']}
else
{$name}

Is there a reason why you need to retain the info? If a user submits the form it will update the info and therefore will need to be fetched again for the next person to come in and update or read.
Above though you assign $year = $oClass ->Year; but it's not referenced anywhere. the $year in the foreach loop is a local scope variable only for that foreach loop, after that loop finishes executing it disappears.
you can do stuff like this.
if (isset($_POST['txtName']))
{
$name = $_POST['txtName'];
}
else
{
$name = '';
}
<input type="text" name="txtName" value="<?php echo $name; ?>" />
Since the only difference between the options in the foreach loops are whether or not the selected attribute is applied you can shorten both of them to the following.
if (isset($_POST['ddlYear'])) {
echo '<option value="' . $year . ($_POST['ddlYear'] == $year) ? '" selected="selected"' : '' . '>' . $year . '</option>';
}
else {
echo '<option value="' . $year . ($movieyear == $year) ? '" selected="selected"' : '' . '>' . $year . '</option>';
}
Also to get a quicker answer please provide the simplest working use case, for example above example has $_POST variables that aren't defined anywhere and others like $movieyear also not defined.

Related

Generating element with php script by the php script

I am trying to learn php and now I am stucked with one thing.
I have the code like this:
<select name = "Option1" id ="Option1">
<option value="0">Option1</option>
<?php
include ("db_connect.php");
$option1 = $pdo->query("SELECT * FROM options");
while($row = $option1->fetch(PDO::FETCH_ASSOC)){
echo '<option value = "' . $row['id'] . '">' . $row['name'] . '</option>';
}
?>
</select>
Which is select element with options from database.
But I need 5 of them and copying this piece of code 5 times just doesn't make sense, or am I wrong?
I tried something like this:
function renderSelect()
{
for ($a = 0; $a < 5; $a++){
echo '<select>
<option value="0">Option ' . $a . '</option>
' . renderOptions($a) . '
</select>';
}
}
function renderOptions(){
include ("db_connect.php");
$option1 = $pdo->query("SELECT * FROM options");
while($row = $option1->fetch(PDO::FETCH_ASSOC)){
echo '<option value = "' . $row['id'] . '">' . $row['name'] . '</option>';
}
}
And then just call the renderSelect, but it's not working how expected.
Can you please give me little advice what to do here?
Thanks a lot I appreciate it!
Try to use return in your second function. If you echo it in the second function, it will add the echo output to the beginning, where you called the function. You create a String, where you add all your options to it and then return that string.
function renderOptions(){
include ("db_connect.php");
$option1 = $pdo->query("SELECT * FROM options");
$string = "";
while($row = $option1->fetch(PDO::FETCH_ASSOC)){
$string .= '<option value = "' . $row['id'] . '">' . $row['name'] . '</option>';
}
return $string;
}
And another point to mention, you are calling renderOption function and passing $a to a function, which takes to parameter.

echo php variable, in html, which is put again in a php variable

I'm trying to return html, to my ajax request.
The ajax request requests a controller method to create a view according to what is clicked.
It's a simple form. But it should have a <select> tag in it.
The <select> tag should display different roles, with one role already selected. which can be assigned to different users.
So I tried creating an object as so:
$roles = $this->database->GetAllRoles();
$selectedRole = $this->database->GetAllRoles()->where('id', '=', $user->roles_id)->first();
foreach($roles as $role){
$selectObject =
'
<option selected value="' . $selectedRole['id'] . '">"' . $selectedRole['name'] . '"</option>
<option value="' . $roles->id . '">"' . $roles->name . '"</option>
';
}
$htmlFinal =
'
<form>
<!-- Form labels and inputs ... -->
<select class="form-control" type="text">
"' . $selectObject . '"
';
This is what it should look like, with a selected option in the form select tag, and more options when opened.
Obviously the above code doesn't work ofcourse, I tried alot of different approaches but I'm kind of stuck right now.
You are using = on the $selectObject variable inside the loop, so, the variable is overriden each iteration. You could use .= to append the HTML in the variable. Then, you shouldn't write the selected option inside the loop, because you will add it several times. Also, you use $roles but in your foreach, the current element is $role.
$selectObject = '<option selected value="' . $selectedRole['id'] . '">"' . $selectedRole['name'] . '"</option>';
foreach ($roles as $role) {
$selectObject .= '<option value="' . $role->id . '">"' . $role->name . '"</option>';
}
Finally, to avoid a duplicate of the selected role, you could add a if to add only other roles.
$selectObject = '<option selected value="' . $selectedRole['id'] . '">"' . $selectedRole['name'] . '"</option>';
foreach ($roles as $role) {
if ($role->id != $selectedRole['id']) {
$selectObject .= '<option value="' . $role->id . '">"' . $role->name . '"</option>';
}
}
Make your foreach loop looklike this:
if(array_key_exists('id',$selectedRole) && $selectedRole['id']==$roles->id)
<option value="' . $roles->id . '" selected >"' . $roles->name . '"</option>
else
<option value="' . $roles->id . '">"' . $roles->name . '"</option>

php: edit selected "select" on button click

I have a select (dropdown) box. On each button click, I'd like it to load previously saved position. My code is:
<select name="myVariables" style="width:150px">
<?php
foreach ( $variables as $var ) {
echo "<option value=\"" . $var . "\"". $var . " </option>";}
?>
</select>
I have a variable $previouslySelected, and every time the button is clicked, this variable can change. I'd like to also change the currently selected option in the select box to the same value. I've tried with:
echo "<option value=\"" . $var . "\" <?=$previouslySelected==$var ? ' selected=\"selected\"' : '';?\>>". $var . " </option>";}
but this doesn't seem to work.
Also, I've tried this but it only works the first time.
How do you submit the form. With GET or POST?
With GET, than you must take the submitted value in this way:
$previouslySelected = isset($_GET['myVariables']) ? $_GET['myVariables'] : '';
Otherwise with POST:
$previouslySelected = isset($_POST['myVariables']) ? $_POST['myVariables'] : '';
In PHP 7 you can also do:
$previouslySelected = $_POST['myVariables'] ?? '';
EDIT: Write your echo more readable.
$selected = ($previouslySelected === $var) ? ' selected="selected"' : '';
echo '<option value="' . $var . '" ' . $selected . '>' . $var . '</option>';

Update drop down from SQL database using PHP

I know this should be simple but I just can't seem to get my head around it.
I have a list of continents in a sql database that I get back using PHP DBO and display in a drop down list. What I then want to do is get the users preferred continent from the sql database and select that one in the list. E.g if the list contains World, Africa, Europe, N America and S America but the users favorite is 'Europe' I want that one selected. $getContinent is the users preference.
while ($row = $continent_results->fetch(PDO::FETCH_ASSOC)) {
if ($getContinent != ''){
echo '<option value="' . $getContinent . '" selected="selected" >' . $row['CONTINENT_NAME'] . '</option>';
}else{
echo '<option value=' . $row['CONTINENT_ID'] . '>' . $row['CONTINENT_NAME'] . '</option>';
}
}
I would be most grateful if someone could set me straight as I have found some examples on the internet but have been unable to get them to work :)
Your code should be like this
while ($row = $continent_results->fetch(PDO::FETCH_ASSOC)) {
//just check if the option id is equal to the chosen value
if ($getContinent != '' && $getContinent==$row['CONTINENT_ID'] ){
echo '<option value="' . $getContinent . '" selected="selected" >' . $row['CONTINENT_NAME'] . '</option>';
}else{
echo '<option value=' . $row['CONTINENT_ID'] . '>' . $row['CONTINENT_NAME'] . '</option>';
}
}
Its simple, as you guessed :D
You would use something like this:
while ($row = $continent_results->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="' . $row['CONTINENT_ID'] . '">' . $row['CONTINENT_NAME'] . '</option>';
}
I hope that helps!
--al
You can use ternary operator
while ($row = $continent_results->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="' . $row['CONTINENT_ID'] .
($getContinent == $row['CONTINENT_NAME']) ? '" selected="selected"' : '"' . '>' .
$row['CONTINENT_NAME'] . '</option>';
}

populate dropdown list from database when editing form MySQL

I am pretty new to PHP and am having a question about dropdown lists. I am trying to get the list to pull from the database and populate the value when a user edits a form but it is not currently working. There are a few examples of this exact same thing on here but I can't quite get it working, it is likely a syntax error on my end...
Here is my code:
echo '<p><label>Is this project targeted toward?</label><select name="proj_targ_tow"><option value="Select...">Select...</option><option value="National Site">National Site</option><option="Local Site">Local Site</option><option value="Regional Site">Regional Site</option><option value="Other">Other</option></select></p>';
And here is the logic to populate the value from the database, the row I am trying to pull from is 'proj_targ_tow'...
$typesArray = array ( 'Select..', 'National Site', 'Local Site', 'Regional Site', 'Other' );
$selectedType = '';
echo 'as;ldfjas;lfmawoiealknfsliu2047a ' . $row['proj_targ_tow'] . '<br />';
foreach($typesArray as $value){
if($value == $row['proj_targ_tow']) {
$selectedType = 'selected="selected"';
}
echo '<option value="' . $value . '" ' . $selectedType . '>' . $value . '</option>';
}
Can any of you coding gods out there help me out?
It looks to me like the $value in your echo statement is out of scope... what happens when you do this?
$typesArray = array ( 'Select..', 'National Site', 'Local Site', 'Regional Site', 'Other' );
foreach($typesArray as $value){
$selectedType = '';
if($value == $row['proj_targ_tow'])
$selectedType = 'selected="selected"';
echo '<option value="' . $value . '" ' . $selectedType . '>' . $value . '</option>';
}

Categories