I have created a contacts database using PHP, MySQL on a XAMPP server.
The page opens with a 'Contacts' table with Add, Edit & Delete buttons.
Add & Delete are working fine.
Edit button opens a modal form with all the usual inputs which are filled in with values from the table row using...
$("#dlgeditContactName").val(ContactName);
$("#dlgeditEmail").val(Email);
etc.
There is also a select element (Contact Type) which is populated using PHP...
<?php
$conn = new mysqli('xxxx', 'xxxx', 'xxxx', 'xxxx') or die ('Cannot connect to db');
$result = $conn->query("select contacttypeid, contacttype from tblcontacttypes");
echo "<select id = 'dlgeditcontacttypeid'>";
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['contacttypeid'];
$name = $row['contacttype'];
echo '<option value = "'.$id.'">'.$name.'</option>';
}
echo "</select>";
?>
The contacttypeid & contacttype are int and string eg.
1, Personal
2, Family
etc.
At the moment this select box acts as expected and user can choose an option during an edit session.
I just don't know the best way to put a default value in this select box based upon what's in the value in the table row.
Filling the other input elements was easy but using the following for the select does not work...
$("#dlgeditcontacttypeid").val(ContactTypeID);
I think I will have to use 'selected' as in ...
<option value="audi" selected>Audi</option>
(from W3Schools), but not sure if this is best or even how to do it.
I thought of a hidden div on the form with the ID but no luck getting the value to PHP
I tried putting some Java inside the PHP ...
echo "<script> function(); </script>";
but it looks 'messy' and I don't believe it's the best approach
There must be a standard method for this issue - anyone had to deal with this?
Is this what you are looking for:
$ContactTypeID = 2; //Considering you have default value with you.
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['contacttypeid'];
$name = $row['contacttype'];
if($id == $ContactTypeID) //If default value and id in loop are same
echo '<option value = "'.$id.'" selected="selected">'.$name.'</option>';
else
echo '<option value = "'.$id.'">'.$name.'</option>';
}
Related
In the dropdown created, it auto selects the first employee name from the list. And when a different employee is selected, the page refreshes with the first employee on the list selected again. Is there a way to make the default selection a blank?
$sql = "SELECT name FROM employee";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) { unset($name); $name = $row['name'];
echo '<option value="'.$name.'">'.$name.'</option>'; }
add default value, like:
while ($row = $result->fetch_assoc()) { unset($name); $name = $row['name'];
echo '<option value="'.$name.'"'.($isDefaultValue ? "selected":"").'>'.$name.'</option>'; }
you need to create $isDefaultValue variable which determines if given record is default, or if you want to create first blank entry use:
echo '<option value="-1" selected>This is only default value, pick real one!</option>';
and then check in your controller if user picked 'default' -1 value or real one
I come to you in dire need.
What I'm trying to do is to make a form with a dropdown menu, that menu is filled by fetching id's from a table.
<form method="post" action="addWorkExperience.php">
<select name="employerSelection">
<?php
$sql = mysqli_query($conn, "SELECT employer_id FROM employers");
while ($row = $sql->fetch_assoc()){
echo "<option value=\"eID\"> " .$row['employer_id'] . "</option>";
}
?>
</select>
And to my understanding my selected option should be accessible through the $_POST variable like so:
$eValue = $_POST['employerselection'];
or:
$sValue = $_POST['eID'];
These variables would be used in my insert query to write my choice back to the SQL database. However, for some reason it just doesn't. Every other inputfield I trow at it works, except the select field.
Am I missing something?
You have a typo, instead of
$eValue = $_POST['employerselection'];
try
$eValue = $_POST['employerSelection'];
In further situations, you can help yourself by simply using
var_dump($_POST);
that will output all variables that $_POST contains
I'm echoing a list of attributes of a row from a table into an option list for the user to pick from which later would be used to be inserted into another table. What I'm trying to do is, to store the 'id' of that row -not using the foreign key- separately, but the 'id' I keep getting is the 'id' of the last row on the list. Here is a snippet to my code:
<?php
$conn = mysqli_connect('localhost', 'root', '', 'database');
$result = mysqli_query($conn, "SELECT * FROM myTable WHERE region = '{$thisRegion}' ");
//$result .= " ");
while ($row = mysqli_fetch_assoc($result))
{
$selected = (isset($_POST['list']) && $_POST['list'] == $row['id']) ? 'selected' : '';
echo "<option value='$row[streetAddress] $row[apt] $row[city] $row[zip] $row[_state] $row[country]' $selected >$row[city] $row[zip] $row[_state] $row[country] $row[streetAddress] $row[apt]</option>";
$thisId= $row['id'];
$_SESSION["thisId"] = $thisId;
}
?>
</select>
Your problem it's on the code
while ($row = mysqli_fetch_assoc($result))
{
...
$thisId= $row['id'];
$_SESSION["thisId"] = $thisId;
}
That code means that on each iteration, $_SESSION["thisId"] will be replaced with the id of the current row, making it so that at the end of the loop only the last row's ID will be there.
The way I think to do this would be to add the id to the option, and print the row just as display.
echo "<option value='{$row['id']}'> {$row['apt']} {$row['city']}... </option>";
Then, the receiving page could read
$selectedRowId = $_GET['optionKey']
I hope that helps, you should read more about php and forms moving forward as it will make your coding easier. Here is one basic tutorial http://www.w3schools.com/php/php_forms.asp
I have a dropdown list of gender. I am getting the values from my table 'candidate' and in this table i have a field which is actually a foreign key to another table.
The field is gender_code_cde, and the table name is gender_code. Now gender_code contains 2 rows. and id and a description. Its structure is like:
1->Male
2->Female
Its being displayed in dropdown list. but I want to get the id 1 if male is selected and id 2 if female is selected. My code is below:
<p>
<label for ="gender">Gender:</label>
<?php
$query = mysql_query("select * from gender_code"); // Run your query
echo '<select name="GENDER">'; // Open your drop down box
//Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query))
{
echo '<option value="'.$row['gender_cde'].'">'.$row['gender_dsc'].'</option>';
}
echo '</select>';
?>
</p>
I am working in codeIgniter.
// this will alert value of dropdown whenever it will change
<script>
function getvalue(val)
{
alert(val);
}
</script>
<p>
<label for ="gender">Gender:</label>
<?php
$query = mysql_query("select * from gender_code"); // Run your query
echo '<select name="GENDER" id="Gender" onchange="getvalue(this.value)">'; // Open your drop down box
//Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query))
{
echo '<option value="'.$row['gender_cde'].'">'.$row['gender_dsc'].'</option>';
}
echo '</select>';
?>
</p>
In Javascript, you can get the value with native JS.
var e = document.getElementById("give-the-select-element-an-id");
var gender_cde = e.options[e.selectedIndex].value;
If, you want it back at the server, it will come in to PHP as $_GET['GENDER'] or $_POST['GENDER'] depending on if the form does a POST or a GET request.
If you are submitting a (POST) form and this is inside that form you can access the the value (id) from CodeIgniter's $_POST wrapper: $this->input->post('GENDER');. I don't use CodeIgniter so I could be wrong, but it will be located in your $_POST array from PHP.
If you just want to replicate the variable somewhere on the page you can just echo it. Or set via js/jQuery with document.getElementById('#something').value = value; or jQuery('#something').html(value);.
You should also change the following:
use a foreach in place of your while:
foreach ($query as $row) {
echo $row['gender_x'] . $row['gender_y'];
}
use the CodeIgniter SQL wrapper instead of depreciated PHP functions. The query part is $this->db->query('SELECT statement goes here');. You should look at your CodeIgniters' version documentation for a more in depth explanation.
EDIT: To make it a bit more clear, an example:
$query = $this->db->query('SELECT * FROM gender_code');
foreach ($query->result() as $row) {
echo '<option value="' . $row->gender_cde . '">' . $row->geneder_dsc . '</option>';
}
This is assuming you have setup the previous calls in CodeIgniter. Please see http://ellislab.com/codeigniter/user-guide/database/examples.html and you may wish to read http://ellislab.com/codeigniter/user-guide/
I'm having an issue in passing a value from a dropdown list that is in a separate PHP file that is being used by jquery.
I ended up getting the values from the dropdown list that isn't posting correctly by using jquery based on the value selected in the first dropdown list. The dropdown list in question is populating correctly, but with the way I have it setup I cannot post the value to the submit PHP page.
I'm pretty sure it has to do with the way I have it setup; however, I'm very new to jquery and was looking for some guidance.
The main PHP Page (the small areas in question)
<select name="department_list" id="department_list" onchange="$('#singleUser').load('get_users.php?nid='+this.value);">
...
<div id="singleUser" class="singleUser">
</div>
The PHP page (get_users) used to fill the values (only the area in question)
echo '<p style="text-align:center">';
echo "
<br />
Select a person to receive the form
<br />";
echo "<select id='userSelect' class='userSelect'>";
if ($id == '50') {
echo "<option value='Done'>Done</option>";
echo "</select>";
}else {
echo "<option value='none'>Select user</option>";
try {
$db = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$stmt = $db->prepare("SELECT dm.empid AS empid, u.name AS name FROM mytable dm
JOIN mytable2 u ON dm.empid = u.id
WHERE dm.deptid = :id
ORDER BY u.name");
$stmt->bindParam(':id', $id);
$stmt->execute();
while ($r = $stmt->fetch()) {
$empid = $r['empid'];
$userName = $r['name'];
echo "<option value='".$empid."'>".$userName."</option>";
}
echo "</select>";
echo "</p>";
$db = null;
}
catch (PDOException $ex) {
echo "An Error occurred!";
}
}//end else
In the submit page:
if(isset($_POST['userSelect'])){
$givenID = $_POST['userSelect'];
//the rest of my code
I do have the div code above within the form tags and have method="post". All of my other inputs post correctly, so I'm thinking it has to do with the way I have only the div tags within the main page. Again, I'm pretty new to all of this so any ideas or changes that I should make so it posts correctly would be greatly appreciated.
You forgot the name of the select when you write it with php:
change this:
echo "<select id='userSelect' class='userSelect'>";
to
echo "<select id='userSelect' name='userSelect' class='userSelect'>";
i think the error is in the PHP file generating the user select it is missing the name attribute name="userSelect"
echo "<select id='userSelect' class='userSelect'>";
it should be
echo '<select id="userSelect" name="userSelect" class="userSelect">';
every form element with the name attribute gets posted with its value. if you do not enter the name attribute, the value can not be retrieved from the $_POST array. Also have in mind that disabled form inputs also do not get posted.
Edited the PHP quotes. Use Single qutes everyt time you do not need to insert PHP variable into the string. It is ~9 times faster than double quotes ;)