Populate more than one drop down using the same mysql query - php

I have form with a number of drop boxes which have the numbers 1-5 in them. I can use this code to populate a drop down but was wondering if I can somehow only make the call to the db once but populate all the drop downs that use the same numbers?
<?php
$sql = "SELECT * FROM riskNumDrop";
$result = $conn->query($sql);
if (!$conn->query($sql)) {
echo "query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
echo '<select class="assess" name="precontcons" style="width:4em">' ;
while($row = $result->fetch_assoc()){echo '<option value='. $row['riskNumDrop'] .'>'.$row['riskNumDrop'].'</option>';}
?> </select>
So Ideally, I generate the output once and reuse it multiple times. Im guessing an array (which $result already is) but how do I populate a drop down from it? TIA

Saving as a string would save you the processing of having to loop through the same data generating the same output multiple times. If this is what you want, you could do the following.
Replace:
echo '<select class="assess" name="precontcons" style="width:4em">' ;
while($row = $result->fetch_assoc()){echo '<option value='. $row['riskNumDrop'] .'>'.$row['riskNumDrop'].'</option>';}
?> </select>
with:
$drop = '<select class="assess" name="precontcons" style="width:4em">' ;
while($row = $result->fetch_assoc()){
drop .= '<option value='. $row['riskNumDrop'].'>'.$row['riskNumDrop'].'</option>';
}
$drop .= '</select>';
Then you can echo $drop several times if you want.
If for whatever reason you want different select attributes, you could just save the options list and print the select around that, like this:
$dropOptions = "";
while($row = $result->fetch_assoc()){
$dropOptions .= '<option value='. $row['riskNumDrop'].'>'.$row['riskNumDrop'].'</option>';
}
Then just echo '<select class="foo" name="bar">'.$dropOptions.'</select'>

You could store the data into an array, and then print the data by enumerating the array.
$risks = array();
// Load values into array.
while ($row = $result->fetch_assoc()) {
array_push($row['riskNumDrop']);
}
// Drop down #1
echo '<select>';
foreach ($risks as $risk) {
echo '<option value='. $risk .'>'. $risk .'</option>';
}
echo '</select>';
// Drop down #2
echo '<select>';
foreach ($risks as $risk) {
echo '<option value='. $risk .'>'. $risk .'</option>';
}
echo '</select>';

Simply get the results into an array using the fetch_all method. It returns all rows from the result set into an associative or numeric array. The you can do whatever you want with such array:
$result = $conn->query('SELECT * FROM riskNumDrop');
if (!$result) {
echo "query failed: (" . $mysqli->errno . ") " . $mysqli->error;
exit; // fetch_* functions cannot be called on error (sice $result is false)
}
// get all rows from the result
$rows = $result->fetch_all(MYSQLI_ASSOC);
// output first dropdown...
echo '<select name="dropdown_1">';
foreach ($rows as $row) {
// options for the first dropdown (same as you did before)
}
echo '</select>';
// output second dropdown...
echo '<select name="dropdown_2">';
foreach ($rows as $row) {
// options for the second dropdown
}
echo '</select>';

Related

Populating drop down list in the PHP variable

while ($row = mysqli_fetch_array($result)){
$move = '
<select type = text name="mover">
<option>select something</option>
'".while ($dbrow = mysqli_fetch_array($result)){
echo "<option value='".$dbrow['deptname']."'>".$dbrow['deptname']."</option>";}."'
</select>';
echo '<tr><td>'.$row['name'].'</td><td>'.$move.'</td></tr>';}
I am trying to display dropdown list inside the table. However whenever I apply while(...) codes, it displays an error.
shouldn't HTML + '".PHP."' + HTML be the correct way?
Generate the select menu before entering the main loop that builds the table and then rewind the recordset so that the main loop can begin
<?php
$html='<select name="mover">
<option selected disabled hidden>Please select something';
while( $row = mysqli_fetch_array( $result ) ){
$html.=sprintf('<option>%s',$row['deptname'] );
}
$html.='</select>';
$result->data_seek(0);
?>
Then build the table.
<table>
<?php
while( $row = mysqli_fetch_array( $result ) ){
printf('<tr><td>%1$s</td><td>%2$s</td></tr>',$row['deptname'],$html);
}
?>
</table>
Don't concatenate. End your string, start your second while loop.
while ($row = mysqli_fetch_array($result)){
$move = '<select name="mover">
<option>select something</option>';
while ($dbrow = mysqli_fetch_array($result)){
$move .= "<option value='".$dbrow['deptname']."'>".$dbrow['deptname']."</option>";
}
$move .= '</select>';
echo '<tr><td>'.$row['name'].'</td><td>'.$move.'</td></tr>';
}
Removed type=text from your <select>.
Replaced your echos with $move .= ... to add to the $move variable.
Be aware that, depending on the number of items in $row this would leave your HTML with multiple <select>s with the same name.
When you use " the php is resolved so you just need to escape the html "s
while ($row = mysqli_fetch_array($result)) {
echo "<tr><td>$row['name']</td><td><select name=\"mover\"><option value=\"\">select something</option>";
while ($dbrow = mysqli_fetch_array($result))
echo "<option value=\"$dbrow['deptname']\">$dbrow['deptname']</option>";
echo "</select></td></tr>";
}

Set previously selected value in Dropdown box using PHP

So, what I'm trying to achieve that after the user hits submit, the dropdown retains the value that the user have chosen. This is my code for the dropdown, I understand that I have to selected = 'selected', but I couldn't figure out how it fits in my code.
if (mysqli_num_rows($result) > 0) { // output data of each row
while($row_branch = mysqli_fetch_array($result)) {
$menu_branch .= "<option value='".$row_branch["0"]."'>" .
$row_branch["0"]. "</option>";
}
}
echo $menu_branch;
You cannot just add selected = selected inside the loop because every option will be selected.
You might need the if statement to select the option of your choice.
For example:
if($row_branch["0"] == 'bar'){
$menu_branch .= "<option value='".$row_branch["0"]."' selected>" .
$row_branch["0"]. "</option>";
}else{
$menu_branch .= "<option value='".$row_branch["0"]."'>" .
$row_branch["0"]. "</option>";
}
When the user select an option, Where you submit this information?
If this information return from a database
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row_branch = mysqli_fetch_array($result)) {
$select = ($row_branch["0"]==$value_db)? "selected='selected'" : "";
$menu_branch .= "<option value='".$row_branch["0"]."' $select>" .
$row_branch["0"]. "</option>";
}
}
if i understand right:
// $yourvalue is previous dropdown value
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row_branch = mysqli_fetch_array($result)) {
if ($row_branch["0"] == $yourvalue)
$selected = "selected";
else
$selected = "";
$menu_branch .= "<option value='".$row_branch["0"]."' $selected>" .
$row_branch["0"]. "</option>";
}
}
echo $menu_branch;

populate drop down list from mysql database and don't repeat values

I am populating a drop down menu from mysql database. It works well, But I want it not to repeat values. (i.e if some value is N times in database it comes only once in the drop down list)
Here is my code:
<?php
mysql_connect('host', 'user', 'pass');
mysql_select_db ("database");
$sql = "SELECT year FROM data";
$result = mysql_query($sql);
echo "<select name='year'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['year'] . "'>" . $row['year'] . "</option>";
}
echo "</select>";
?>
Use DISTINCT in your query.
"SELECT DISTINCT year FROM data";
just change Your query. is better
$sql = "SELECT distinct year FROM data";
Another technique:
select year from table group by year
in PHP side you have to do this
$all_data = array();
echo "<select name='year'>";
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
array_push($all_data,$row["column"]);
}
$all_data = array_unique($all_data);
foreach($all_data as $columns => $values){
print("<option value='$value'>$value</option>");
}
echo "</select>";
Here is a simple trick. Take a boolean array. Which value has not come in list print it in list and which value has come in list already once, set it as true through indexing the boolean array.
Set a condition, if boolean_array[ value ] is not true, then show value in list. Otherwise, don't.
mysql_connect('host', 'user', 'pass');
mysql_select_db ("database");
$sql = "SELECT year FROM data";
$result = mysql_query($sql);
echo "<select name='year'>";
while ($row = mysql_fetch_array($result)) {
if($bul[$row['year']] != true){
echo "<option value='" . $row['year'] . "'>" . $row['year'] . " </option>";
$bul[$row['year']] = true;
}
}
echo "</select>";
?>

dynamic populate a select input from mysql

Hi I am trying to populate an entire Drop down list with MySQL but I cant get it to work, can you please help?
My code:
$database=& JFactory::getDBO();
$database->setQuery('SELECT training_id,training,trainingDate FROM training ');
$result = $database->loadObjectList();
echo '<select name="whatever">';
while($row = mysql_fetch_array($result)) {
echo '<option value="$row[training_id" />';
}
echo '</select>';
Your echo string doesn't allow for embedded variables because you are using single quotes instead of double quotes.
Implement this echo instead:
echo '<option value="' . $row["training_id"] . '" />';
Without knowing what the output is, it's hard to know whether this is the only issue, but the glaring error in your code is this:
echo '<option value="$row[training_id" />';
Because this is in single quotes, the variable is not interpreted. You need to use double quotes (and close the square brackets!):
echo "<option value=\"{$row['training_id']}\" />";
Note that I have changed the style of variable interpretation to use curly brackets: I believe this is easier to read and clearer.
In addition to using single quotes, you are also:
Missing a closing square bracket.
Missing the closing tag for the <option>.
You probably want to change your output to something like this, so you display some option text to the user:
echo '<select name="whatever">';
while($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['training_id'] . '"> ' . $row['training'] . '</option>';
}
echo '</select>';
$database= &JFactory::getDBO();
$database->setQuery('SELECT training_id,training,trainingDate FROM training');
$result = $database->loadObjectList();
echo '<select name="whatever">';
foreach ($result as $row) {
echo '<option value="'.$row->training_id.'" />';
}
echo '</select>';
Use #__ for table prefix.
$database= &JFactory::getDBO();
$database->setQuery('SELECT training_id,training,trainingDate FROM training');
$result = $database->loadObjectList();
echo '<select name="whatever">';
foreach ($result as $row) {
echo '<option value="'.$row->training_id.'" />';
}
echo '</select>';
This code works, but populates the list with empty options. I had to put a simple echo in as shown below, and works just fine. For some reason, $row->teremnev is empty for me. Im sure this is not the right way, but it works.
$db =& JFactory::getDBO();
$query = "SELECT teremnev FROM #__teremlista";
$db->setQuery($query);
$result = $db->loadResultArray();
echo '<select name="termek">' ;
foreach ($result as $row) {
echo '<option value="'.$row->teremnev.'" />';
echo $row;
}
echo '</option>';
echo '</select>';
<select>
<option>Select Training</option>
while($row = mysqli_fetch_array($result))
{
echo "<option>". $row['training_name']."</option>";
}
</select>

How to echo out table rows from the db (php)

i want to echo out everything from a particular query. If echo $res I only get one of the strings. If I change the 2nd mysql_result argument I can get the 2nd, 2rd etc but what I want is all of them, echoed out one after the other. How can I turn a mysql result into something I can use?
I tried:
$query="SELECT * FROM MY_TABLE";
$results = mysql_query($query);
$res = mysql_result($results, 0);
while ($res->fetchInto($row)) {
echo "<form id=\"$row[0]\" name=\"$row[0]\" method=post action=\"\"><td style=\"border-bottom:1px solid black\">$row[0]</td><td style=\"border-bottom:1px solid black\"><input type=hidden name=\"remove\" value=\"$row[0]\"><input type=submit value=Remove></td><tr></form>\n";
}
$sql = "SELECT * FROM MY_TABLE";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!! Check summary get row on array ..
echo "<tr>";
foreach ($row as $field => $value) { // I you want you can right this line like this: foreach($row as $value) {
echo "<td>" . $value . "</td>"; // I just did not use "htmlspecialchars()" function.
}
echo "</tr>";
}
echo "</table>";
Expanding on the accepted answer:
function mysql_query_or_die($query) {
$result = mysql_query($query);
if ($result)
return $result;
else {
$err = mysql_error();
die("<br>{$query}<br>*** {$err} ***<br>");
}
}
...
$query = "SELECT * FROM my_table";
$result = mysql_query_or_die($query);
echo("<table>");
$first_row = true;
while ($row = mysql_fetch_assoc($result)) {
if ($first_row) {
$first_row = false;
// Output header row from keys.
echo '<tr>';
foreach($row as $key => $field) {
echo '<th>' . htmlspecialchars($key) . '</th>';
}
echo '</tr>';
}
echo '<tr>';
foreach($row as $key => $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}
echo("</table>");
Benefits:
Using mysql_fetch_assoc (instead of mysql_fetch_array with no 2nd parameter to specify type), we avoid getting each field twice, once for a numeric index (0, 1, 2, ..), and a second time for the associative key.
Shows field names as a header row of table.
Shows how to get both column name ($key) and value ($field) for each field, as iterate over the fields of a row.
Wrapped in <table> so displays properly.
(OPTIONAL) dies with display of query string and mysql_error, if query fails.
Example Output:
Id Name
777 Aardvark
50 Lion
9999 Zebra
$result= mysql_query("SELECT * FROM MY_TABLE");
while($row = mysql_fetch_array($result)){
echo $row['whatEverColumnName'];
}
$sql = "SELECT * FROM YOUR_TABLE_NAME";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!!
echo "<tr>";
foreach ($row as $field => $value) { // If you want you can right this line like this: foreach($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
In PHP 7.x You should use mysqli functions and most important one in while loop condition use "mysqli_fetch_assoc()" function not "mysqli_fetch_array()" one. If you would use "mysqli_fetch_array()", you will see your results are duplicated. Just try these two and see the difference.
Nested loop to display all rows & columns of resulting table:
$rows = mysql_num_rows($result);
$cols = mysql_num_fields($result);
for( $i = 0; $i<$rows; $i++ ) {
for( $j = 0; $j<$cols; $j++ ) {
echo mysql_result($result, $i, $j)."<br>";
}
}
Can be made more complex with data decryption/decoding, error checking & html formatting before display.
Tested in MS Edge & G Chrome, PHP 5.6
All of the snippets on this page can be dramatically reduced in size.
The mysqli result set object can be immediately fed to a foreach() (because it is "iterable") which eliminates the need to maked iterated _fetch() calls.
Imploding each row will allow your code to correctly print all columnar data in the result set without modifying the code.
$sql = "SELECT * FROM MY_TABLE";
echo '<table>';
foreach (mysqli_query($conn, $sql) as $row) {
echo '<tr><td>' . implode('</td><td>', $row) . '</td></tr>';
}
echo '</table>';
If you want to encode html entities, you can map each row:
implode('</td><td>' . array_map('htmlspecialchars', $row))
If you don't want to use implode, you can simply access all row data using associative array syntax. ($row['id'])

Categories