I'm trying to modify a function that I've been using to dynamically populate <select> element to use arrays from a database. The original function used hard-coded arrays to populate the elements, and pre-selected the option which matched the db value.
The revised function creates the element, but it's only adding the first value from the db. How can I modify it so that it will loop through all the values that should be added to the <select> element?
PHP Function and Query
<?php
function printSelectOptions($dataArray, $currentSelection) {
foreach ($dataArray as $key => $value) {
echo '<option ' . (($key == $currentSelection)) . ' value="' . $key . '">' . $value . '</option>';
}
}
try {
$stmt = $conn->prepare("SELECT * FROM student");
$stmt->execute();
}catch(PDOException $e) {
echo $e->getMessage();
}
$row = $stmt->fetch();
?>
Populate Select Element
<select name="fname">
<?php
echo printSelectOptions(array($row['fname']));
?>
</select>
The Original Function & Code for Populating an Element
function printSelectOptions($dataArray, $currentSelection) {
foreach ($dataArray as $key => $value) {
echo '<option ' . (($key == $currentSelection) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>';
}
}
<select name="fname">
<?php
$options = array("John"=>"John", "Mary"=>"Mary", "Elizabeth"=>"Elizabeth");
$selected = $row['fname'];
echo printSelectOptions($options, $selected);
?>
</select>
Since you have only fetched a single row via fetch(), only a single value is getting passed into your function printSelectOptions(). Instead, get all rows via fetchAll()
and modify your function to receive the full array, plus a string which is the column name (array key) you want to print from.
// All rows into $rows...
$rows = $stmt->fetchAll();
// Make the function accept the full 2D array, and
// a string key which is the field name to list out:
function printSelectOptions($dataArray, $currentSelection, $fieldname) {
// String to hold output
$output = '';
foreach ($dataArray as $key => $value) {
// Rather than echo here, accumulate each option into the $output string
// Use the $fieldname as a key to $value which is now an array...
$output .= '<option ' . (($key == $currentSelection)) . ' value="' . $key . '">' . htmlspecialchars($value[$fieldname], ENT_QUOTES) . '</option>';
}
return $output;
}
Then call the function as:
echo printSelectOptions($rows, $currentSelection, 'fname');
The way it is right now, the option's value attribute is populated by the array key, which would be numbered from zero. That's similar to your original array version, but it might be more useful to specify another column name like id as the key column.
// This one also takes a $valuename to use in place of $key...
function printSelectOptions($dataArray, $currentSelection, $valuename, $fieldname) {
// String to hold output
$output = '';
foreach ($dataArray as $key => $value) {
// Rather than echo here, accumulate each option into the $output string
// Use the $fieldname as a key to $value which is now an array...
$output .= '<option ' . (($value[$valuename] == $currentSelection)) . ' value="' . $value[$valuename] . '">' . htmlspecialchars($value[$fieldname], ENT_QUOTES) . '</option>';
}
return $output;
}
And would be called as:
echo printSelectOptions($rows, $currentSelection, 'id', 'fname');
Related
I am using the following code. I take some values from an xml, then I use as html option. I am using almost the same code for the first and second select. First option show in the select menu the right values: http://vilavaleaprahovei.ro/kimea/anvelope.php, but the other one shows 0. Could somebody to tell me what to do on the "Eficienta combustibil" to show the right values?
<form action="anvelope.php" method="post">
<?php
$jante = "http://vilavaleaprahovei.ro/kimea/feeds/alcarRO_feed.xml";
$xml=simplexml_load_file($jante);
$items = [];
$limitItems = 0;
foreach($xml->Produs as $child)
{
$marca = (string)$child->Marca;
if(!isset($items[$marca])) {
$items[$marca] = [];
}
$items[$marca]['sarcina'][] = (int)$child->Sarcina;
$items[$marca]['eficienta_combustibil'][] = (float)$child->Eficienta_Combustibil;
}
//SARCINA
$option_arr9 = array_column($items,'sarcina');
function generate_option9($item, $key)
{
echo "<option value='" . $item . "'>" . $item . "</option>";
}
$options = array_unique($option_arr9[0], SORT_STRING); // You can add array_unique and SORT_NUMERIC here
asort($options);
echo "<select name='sarcina'><option>Sarcina</option>";
array_walk_recursive($options, 'generate_option9');
echo "</select>";
//EFICIENTA COMBUSTIBIL
$option_arr10 = array_column($items,'eficienta_combustibil');
function generate_option10($item, $key)
{
echo "<option value='" . $item . "'>" . $item . "</option>";
}
$options = array_unique($option_arr10[3], SORT_STRING); // You can add array_unique and SORT_NUMERIC here
asort($options);
echo "<select name='eficienta_combustibil'><option>Eficienta Combustibil</option>";
array_walk_recursive($options, 'generate_option10');
echo "</select>";
?>
</form>
This is my goal trying to remove duplicates and also keep matched from the exploded value and the $classQuery statement selected
$examQuery = $examClass->get_examByID($id);
$examRow = $examQuery->fetch_assoc();
$classes = explode(',', $examRow['class_id']);
$classQuery2 = $con->query("SELECT * FROM `class` WHERE `school_id` = '{$examRow['school_id']}' ");
if ($classQuery2->num_rows < 1):
$output .= '';
else:
while ($class_rows = $classQuery2->fetch_assoc()):
foreach ($classes as $class):
if ($class_rows['class_id'] === $class):
$output .= '<option selected value="' . $class_rows['class_id'] . '">' . $class_rows['class_title'] . '</option>';
else:
$output .= '<option value="' . $class_rows['class_id'] . '">' . $class_rows['class_title'] . '</option>';
endif;
endforeach;
endwhile;
endif;
You should be able to resolve this simply by putting a GROUP BY on your query;
$classQuery2 = $con->query("SELECT * FROMclassWHEREschool_id= '{$examRow['school_id']}' GROUP BY class_id");
Otherwise, I'd probably keep an array of ones already used and check if the key is in that before echoing;
For example;
// the array of items to loop over (which has a duplicate in it)
$myArray = ['english', 'maths', 'science', 'geography', 'english'];
// an array to place the item name when it's been used once
$alreadyUsed = [];
foreach($myArray as $item) {
// if the item doesn't already exist in $alreadyUsed then
// echo it out and add it to the array.
if (! in_array($item, $alreadyUsed)) {
echo $item . "<br>";
$alreadyUsed[] = $item;
}
}
You are comparing different Types!
If you want a good comparasion, you'll need to compare the values with the same type
e.g Integer === Integer || String === String || Object === Object
In your case, you have to compare the $class_rows['class_id'] with your class ID,
Something like that:
if ($class_rows['class_id'] === $class.id):
# Successful Condition
else:
# Unsuccesful Condition
endif;
I have very little experience with PHP, but I'm taking a class that has PHP review exercises. One of them is to create a function that uses a loop to return all values of an array except the first value in an unordered list. I'm assuming there's a way to do this using a foreach loop but cannot figure out how. This is what I had but I feel like I am far off:
<?php
$array = array('myName' => 'Becca', 'favColor' => 'violet', 'favMovie' => 'Empire Strikes Back', 'favBook' => 'Lullaby', 'favWeb' => 'twitter.com');
$myName = $array['myName'];
$favColor = $array['favColor'];
$favMovie = $array['favMovie'];
$favBook = $array['favBook'];
$favWeb = $array['favWeb'];
echo '<h1>' . $myName . '</h1>';
function my_function() {
foreach($array == $myName){
echo '<ul>'
. '<li>' . $favColor . '</li>'
. '<li>' . $favMovie . '</li>'
. '<li>' . $favBook . '</li>'
. '<li>' . $favWeb . '</li>'
. '</ul>';
}
}
my_function();
?>
The correct syntax of foreach is
foreach (array_expression as $key => $value)
instead of
foreach($array == $myName){
function that uses a loop to return all values of an array except the
first value
I'm not sure, what exactly you mean by except the first value. If you are trying to remove first element from the array. Then you could have used array_shift
If you are supposed to use loop then
$count = 0;
foreach ($array as $key => $value)
{
if ($count!=0)
{
// your code
}
$count++;
}
Change the code to following
<?php
$array = array('myName' => 'Becca', 'favColor' => 'violet', 'favMovie' => 'Empire Strikes Back', 'favBook' => 'Lullaby', 'favWeb' => 'twitter.com');
$myName = $array['myName'];
echo '<h1>' . $myName . '</h1>';
function my_function($array)
{
$count = 0;
echo "<ul>";
foreach($array as $key => $value)
{
if($key != "myName")
{
echo "<li>".$value."</li>";
}
}
echo "</ul>";
}
my_function($array);
I'm working with the Filemaker API - which is similar to sql - basically its pulling data from a fields and from a list.
I'm trying to set up an if statement inside my foreach loop so that it adds a the tag selected="selected" to my select option in my html
Here's the code
<?php
$layout =& $fm->getLayout('Leads');
$values = $layout->getValueList('LeadStatus');
$list_menu = '<select name="LeadDocStatusSelect">';
foreach ($values as $value)
{
$list_menu .='<option value="' . $value . '">' . $value . '</option>' ;
}
$list_menu .= '</select>';
echo $list_menu;
?>
How can I add an if statement like this to the foreach loop?
if ($businessJudgements == 'No') {
echo 'checked="checked"';
} else {
echo '';
}
The body of the foreach loop is simply a block of statements so you can put in as many as you want, such as with:
foreach ($values as $value) {
$list_menu .='<option value="' . $value . '">' . $value . '</option>';
if ($businessJudgements == 'No') {
echo 'checked="checked"';
} else {
echo '';
}
}
However, are you sure you have the right attribute for the option tag? If it's your intent to select a specific option, checked is not the right method (it's meant for checkbox input fields). The selected attribute is the correct one for the HTML option tag.
So you would be better off with something like:
# The default is orange.
$default_value = "orange";
# Process every option.
foreach ($values as $value) {
# Add [<option value="X"].
$list_menu .= '<option value="' . $value . '"';
# Add [ selected] ONLY for default one.
if ($value == $default_value) {
$list_menu .= ' selected';
}
# Add [>X</option>].
$list_menu .= '>' . $value . '</option>';
}
This will give you the option tags as desired but the one where the value matches the default value will also have the selected attribute attached.
Assuming $values held the array {"red", "black", "orange", "yellow"}, you would end up with (formatted nicely here for the purposes of the answer):
<option value="red"> red </option>
<option value="black"> black </option>
<option value="orange" selected> orange </option>
<option value="yellow"> yellow </option>
I assuming that you already know how to get your $businessJudgement , so that code should be something like this
<?php
$layout =& $fm->getLayout('Leads');
$values = $layout->getValueList('LeadStatus');
$list_menu = '<select name="LeadDocStatusSelect">';
foreach ($values as $value)
{
if ($businessJudgements == 'No') {
$list_menu .='<option value="' . $value . '">' . $value . '</option>' ;
} else {
$list_menu .='<option value="' . $value . '" selected >' . $value . '</option>' ;
}
}
$list_menu .= '</select>';
echo $list_menu;
?>
I'm still a PHP noob, so I apologize if this is something simple.
I am creating a fairly basic search facility for a website using PHP and mySQL. I have connected to the database, selected the database, queried the table and have fetched the table columns;
$k = htmlspecialchars($_GET['k']); // Get search query
$select = mssql_query("SELECT * FROM search WHERE Title Like '%" . $k . "%'");
if( mssql_num_rows($select) < 1) {
$noResults = 'No results found for <b>' . $k . '</b>, <label for="k">Please try again.</label>';
} else {
while ($results = mssql_fetch_array($select)) {
$title = $results['Title'];
$link = $results['Link'];
$description = $results['Description'];
}
}
When I put the $results[''] columns into variables and then try to echo out each variable like so;
if( isset($noResults)) {
echo $noResults;
} else {
echo '<li>' . '<h2>' . '' . $title . '' . '</h2>' . '<p>' . $link . '</p>' . '<p>' . $description . '</p>' . '</li>';
}
it only echo's out one row matching that query however, If I was to just simple echo out the columns like so;
echo $results['Title'];
echo $results['Link'];
echo $results['Description'];
all rows matching the query will be displayed..
I'm not sure why this is happening. If someone could help me out that would be great!
You need to use a loop:
$k = mysql_real_escape_string($_GET['k']); // Get search query
$select = mssql_query("SELECT * FROM search WHERE Title Like '%" . $k . "%'");
if( mssql_num_rows($select) < 1) {
$noResults = 'No results found for <b>' . $k . '</b>, <label for="k">Please try again.</label>';
} else {
$results= array();
while ($result = mssql_fetch_array($select)) {
$results[]= $result;
}
}
if( isset($noResults)) {
echo $noResults;
} else {
echo "<ul>";
foreach($results as $result){
echo '<li>' . '<h2>' . '' . $result['title'] . '' . '</h2>' . '<p>' . $result['link'] . '</p>' . '<p>' . $result['description'] . '</p>' . '</li>';
}
echo "</ul>";
}
Do you execute the output in the while-loop?
If you execute the while-loop and call the echo after that, each resultset will overwrite the previous, and the echo will output the last resultset which was fetched.
If you call the echo in the Loop, every result set will generate "his own" output line.
If you want to hold every resultset in a variable you can use an array, which is declared in front of the loop and gets filled in the loop.
a few things are not clear from your question, but i am assuming that you are echo'ing the variables outside the loop since you are checking isset($noResults). that means you are reassigning the variables with new values in each loop of while. so ultimately you get the last one assigned to the variables. you have to either use an array to hold the values or echo it with in the loop.