I want to create a dropdown filled with numbers. These numbers need to be retrieved from a database. The connection to the database and the supposed display code are as follows:
The Function to retrieve the options for the dropdown
<?php
function dropdown_menu() {
global $wpdb;
/* Query the database */
$query = $wpdb->prepare('SELECT * FROM LID ORDER BY LidID', 'LID', 'LidID');
$results = $wpdb->get_results($query);
/* Check for $results */
if(!empty($results)) :
/* Loop through the $results and add each as a dropdown option */
global $options;
$options = '';
foreach($results as $result) :
echo ("<option value=\"<?php echo $item->LidID ?>\"> <?php echo $item->LidID ?> </option>");
endforeach;
endif;
}
?>
The statement which includes the aforementioned function into a form:
<tr class="form-field form-required">
<th scope="row"><label for="LidID">Lid ID <span class="description">(verplicht)</span></label></th>
<td><select name="LidID" id="LidID" value="<?php echo $item->LidID ?>" aria-required="true"> <?php dropdown_menu(); ?> </select></td>
</tr>
The problem I'm having, is that it creates a dropdown list with the corresponding amount of records of "LidID" in the database, but they all show up blank. I've already been toying around with it, and I think I know what the problem is, but I don't know how to solve it. I presume the problem lies within the echo-statement;
echo ("<option value=\"<?php echo $item->LidID ?>\"> <?php echo $item->LidID ?> </option>");
when I remove the second LidID ?> and replace it with, for example, a 5, it shows a list of fives. For some reason it doesn't recognize the statement I wrote. I've tried to switch out both the $item->LidID in the echo statement into $result->LidID, but that doesn't seem to have any impact. Does anyone have the slightest idea of what is going wrong here?
Oh yeah, I don't know if it's relevent but it's a plug-in for wordpress.
You're right, that is the issue. You are already in PHP when echoing, so you don't need to open more PHP tags. The other issues is $item doesn't exist. Another issue is you're not using MySQLi correctly, you only use prepare if you have a variable, you don't so don't use it. You also don't use get_results in that context. Try this:
function dropdown_menu($default) {
global $wpdb;
/* Query the database */
$query = 'SELECT * FROM LID ORDER BY LidID, LID, LidID';
$results = $wpdb->query($query);
while ($item = $results->fetch_assoc()):
echo '<option value="'.$item->LidID.'"'.($item->LidID == $default ? ' selected="selected"' : '').'>'.$item->LidID.'</option>';
endwhile;
}
Then when calling the function
<td>
<select name="LidID" id="LidID" aria-required="true"> <?php dropdown_menu($item->LidID); ?> </select>
</td>
Related
I am writing a program that allows the user to update customer information. One of the fields that can be updated is the country that the customer is from. The country can be updated using a dropdown menu that pulls all of the country names from an SQL database and is dynamically generated using a for loop. However, I also want to program the dropdown menu to automatically select the country that the customer is from. Is there a way to do this while keeping the for loop?
<label>Country:</label>
<select name="countryCode">
<?php foreach ($countries as $country) : ?>
<option value="<?php echo $country['countryCode']; ?>"><?php echo $country['countryName']; ?></option>
<?php endforeach; ?>
</select>
Code for pulling customer data from the database.
$customer_id = filter_input(INPUT_POST, 'customerID');
if ($customer_id == NULL || $customer_id == FALSE) {
$error = "Missing or incorrect customer ID.";
include('../errors/error.php');
} else {
$customers = select_customer($customer_id);
$countries = get_countries();
include('customer_update.php');
}
}
function select_customer($customer_id) {
global $db;
$query = 'SELECT * FROM customers
WHERE customerID = :customer_id';
$statement = $db->prepare($query);
$statement->bindValue(':customer_id', $customer_id);
$statement->execute();
$select = $statement->fetch();
$statement->closeCursor();
return $select;
}
Code for pulling country data.
function get_countries() {
global $db;
$query = 'SELECT * FROM countries
ORDER BY countryName';
$statement = $db->prepare($query);
$statement->execute();
$countries = $statement->fetchAll();
$statement->closeCursor();
return $countries;
}
You should add the selected tag to an option depending on the data. It could be something like this:
<label>Country:</label>
<select name="countryCode">
<?php foreach ($countries as $country) : ?>
<option value="<?php echo $country['countryCode']; ?>" <?=($country['countryCode'] == $customers['country_code']) ? 'selected' : '' ?>><?php echo $country['countryName']; ?></option>
<?php endforeach; ?>
</select>
I assumed here that your customer data ($customers variable) has the country_code field.
I hope you've got the idea.
PS: the <?= statement is a kind of a shortcut to the <?php echo.
I managed to get it worked out. The code <option value="<?php echo $country['countryCode']; ?>"<?=($country['countryCode'] == $customers['countryCode']) ? 'selected' : '' ?>><?php echo $country['countryName']; ?></option> seems to do the trick. I did notice that changes in the dropdown menu code did not apply when I refresh the page, but do apply if I manually travel back to the page.
Not experienced with creating forms in PHP.
I can get my form to produce a dropdown list that has one of my rows listed as an option, but as soon as I try to concatenate 2 rows together (from the same table) for option output...
a) It just doesn't work and I get errors
b) I get the first row as a single option, then my next row as a separate option.
I know there is a simple solution to this, but I am an online student just learning, and I can't seem to find a good example of the code to write it. I'm pretty sure it's an issue of quotes not being placed correctly.
MySQLTable Data:
Table Name: courses
Table Rows: course_id, course_name, max_enrolment
Sample Data: LO-COMP-8001, Intro to HTML, 20
function select_course(){
global $open;
$select = "SELECT * FROM courses";
$result = mysqli_query($open, $select);
return $result;
}
<form action="insert.php" method="post">
<dl>
<dt>Select Course</dt>
<dd><select name="course_id">
<?php // CREATE dropdown menu
$result = select_course();
while ($row = mysqli_fetch_assoc($result)) {
foreach ($row as $selection) {
echo "<option value=\"$selection\">$selection</option>";
}}
?>
</select>
</dd>
</dl>
Then there are a few more form fields such as student name and student id afterwards...
Goal Output:
course_id course-name
"LO-COMP-8001 Intro to HTML" ... as a single connected dropdown option and other remaining courses in a dropdown menu
Current Output:
LO-COMP-8001 (as an option)
Intro to HTML (as another option! ... No good)
20 (must be hidden, I need to check if course is full in another function and either allow or deny a student to enrolled etc.)
I have tried:
// output is the one mentioned above..
echo "<option value=\"$selection\">$selection</option>";
// or alternatively...
echo '<option value="'.$row['course_id'].'">'.$row['course_id'].'</option>';
But the second option creates all kinds of weird results.
This is what I am experimenting with right now...
echo '<option value="'.$row['course_id'] $row['course_name']'">'.$row['course_id'] $row['course_name'].'</option>';
But there is a bunch of issues with quotes and square brackets, and I just don't know how to format it correctly for the output.
Any assistance is appreciated.
$row holds the entire row as an associative array therefore no need for the 'foreach' loop.
function select_course(){
global $open;
$select = "SELECT * FROM courses";
$result = mysqli_query($open, $select);
return $result;
}
<form action="insert.php" method="post">
<dl>
<dt>Select Course</dt>
<dd><select name="course_id">
<?php // CREATE dropdown menu
$result = select_course();
while ($row = mysqli_fetch_assoc($result)) {?>
<option value="<?php echo $row["course_id"]; ?>"><?php echo $row["course_name"]; ?></option>
<?php }
?>
</select>
</dd>
</dl>
</form>
I was able to come up with another solution as well:
Once the foreach loop was removed, I tried cleaning up the code some... I'm not sure if this is uncommon or 'bad' style, but it does work.
$result = select_course();
while ($row = mysqli_fetch_assoc($result)) {
$course_id = $row['course_id'];
$course_name = $row['course_name'];
echo "<option value=\"$course_id\">$course_id $course_name</option>";
Results in: LO-COMP-8001 Intro to HTML as a single option, plus all my other courses in the database.
I need some help in populating a drop down down list from a mysql table. I'm new to php and I am having a hard time. Here's my code and I know it's wrong, I just don't know where.
My current output is just a drop down box with nothing inside it.
My expected output is that it would show the driver's name from the mysql table.
<?php
$Hehe = $mydb->getALL('SELECT drivername FROM driver;'); //select from all users
?>
<select name=mydriver value=''>Driver Name</option> // list box select command
<?php
foreach($Hehe as $hehe){//Array or records stored in $row
?>
<option name = "mydriver"><?phpecho $Hehe['drivername']?></option>
</select>
<?php
}
?>
the getALL function:
function getAll($query) {
$result = $this->conn->prepare($query);
$ret = $result->execute();
if (!$ret) {
echo 'PDO::errorInfo():';
echo '<br />';
echo 'error SQL: '.$query;
die();
}
$result->setFetchMode(PDO::FETCH_ASSOC);
$reponse = $result->fetchAll();
return $reponse;
}
You're using wrong array to get the drivername. It should be $hehe['drivername'], not $Hehe['drivername']. Like I said, use some meaningful variable names in your code, it would be easy for you track down the error. Also </select> should be outside of foreach loop.
<?php
$Hehe = $mydb->getALL('SELECT drivername FROM driver;'); //select from all users
?>
<select name="mydriver">Driver Name</option> // list box select command
<?php
foreach($Hehe as $hehe){//Array or records stored in $row
?>
<option value="<?php echo $hehe['drivername']; ?>"><?php echo $hehe['drivername']; ?></option>
<?php
}
?>
</select>
Sidenote: Always turn on error reporting, add these two statements ini_set('display_errors', 1); error_reporting(E_ALL);at the very top of your PHP scripts to debug any syntax related issues.
I want to do the next thing but I don't know how to do this, I'll try to explain me
I have an field generated by php code like this (Works)
<select id="profiles_select" name="profiles_select">
<?php
do {
?>
<option value="<?php echo strtoupper($system['profile']);?>">
<?php echo strtoupper($system['profile']);?></option>
<?php
} while($system = mysql_fetch_assoc($r)); //the "$r" it's the query
$rows = mysql_num_rows($r);
if($rows > 0) {
mysql_data_seek($r, 0);
$systemas = mysql_fetch_assoc($r);
}
?>
</select>
The query
<?php
$q="SELECT DISTINCT profile FROM sys_profiles";
$r=mysql_query($q,$ConecLocal) or die(mysql_error());;
$systemas=mysql_fetch_assoc($r);
$tsys=mysql_num_rows($r);
?>
What I need?
I need generate another similar to first generated by php code but, this time I need made a Query including the value of the first , something like this:
<?php
$value_select=$_GET['profiles_select'];
$q2="SELECT DISTINCT systems FROM sys_profiles where profile=$value_select";
$r2=mysql_query($q,$ConecLocal) or die(mysql_error());;
$profiles2=mysql_fetch_assoc($r);
$tsys=mysql_num_rows($r);
?>
Next of the query I need show in the another the query result, something similar to the first select (generated by php), but do the query when the first of the it's selected
<select id="systems_select" name="system_select">
<?php
do {
?>
<option value="<?php echo strtoupper($system['systems']);?>">
<?php echo strtoupper($profiles2['systems']);?></option>
<?php
} while($profiles2 = mysql_fetch_assoc($r2)); //the "$r2" it's the another query
$rows2 = mysql_num_rows($r2);
if($rows2 > 0) {
mysql_data_seek($r2, 0);
$systemas = mysql_fetch_assoc($r2);
}
?>
</select>
Thanks for the help.
I've a bug in a search engine showing results.
Here's the code:
$nmanufacturer = $tApplication[2];
$manufac = mysql_query("SELECT * FROM tManufacturers WHERE nManufacturer='$nmanufacturer'");
$manufacts = mysql_fetch_array($manufac);
//nom du constructeur
$contruct = $manufacts[1];
?>
<select class="form-control">
<option><?php echo $contruct; ?></option>
</select>
The probleme is that the option element shows only one result however there's many results in the database Hope you can Help Me Guys!
Bon jour! You have to do a while cicle.
$nmanufacturer = $tApplication[2];
$manufac = mysql_query("SELECT * FROM tManufacturers WHERE Manufacturer='$nmanufacturer'");
?>
<select class="form-control">
<?php
while($manufact = mysql_fetch_array($manufac)) {
echo '<option>' . $manufact[1] . '</option>';
}
?>
</select>
The mysql_fetch_array function returns an associative array, but it also returns FALSE if there are no more rows to return! Using a PHP While Loop we can use this information to our advantage.
If we place the statement "$row = mysql_fetch_array()" as our while loop's conditional statement we will accomplish two things:
We will get a new row of MySQL information that we can print out
each time the while loop checks its conditional statement.
When there are no more rows the function will return FALSE causing the
while loop to stop!
via http://www.tizag.com/mysqlTutorial/mysqlfetcharray.php