Populate multi-select with php while loop from db - php

The following worked on a local environment. Now that it's pushed
live everything but these seems to work. Displays completely empty select boxes now no checks or blank labels just empty space in the "select options" drop down.
select display
<?php
$selected = array();
$selected = explode(",",$fill['markets']);
$condb = mysql_query("SELECT * FROM `countries`");
$count = mysql_num_rows($condb);
$countries = array();
$str;
while ($countries = mysql_fetch_array($condb))
{
$str = "option{$countries['id']}";
echo "<option value='{$str}' ";
if(in_array($str,$selected)) {
echo "selected>";
echo $countries['country'];
echo "</option>";
} else {
echo ">";
echo $countries['country'];
echo "</option>";
}
}
?>

You should use while loop instead. You can declare $i outside the loop if you need it, Try the following code:
$condb = mysql_query("SELECT * FROM `countries`");
$i = 0;
while($countries = mysql_fetch_array($condb)) {
$str = 'option' . $i;
echo "<option value='{$str}' ";
if(in_array($str,$selected)) {
echo "selected>";
echo $countries['country'];
echo "</option>";
} else {
echo ">";
echo $countries['country'];
echo "</option>";
}
$i++;
}
?>
</select>
Note:
mysql_* is deprecated as of php-5.5. So instead use mysqli_* or PDO.
Why shouldn't I use mysql_* functions in PHP?

Related

how to output mysql table data into an html table without knowing what $row is like phpmyadmin

Ok so I'm trying to make a localhost site that has the same base functions as Phpmyadmin, and everything is working other than displaying a table's data.
here's an example of what I'm trying to accomplish:
though I'm not sure how to accomplish this. Here is some code to show you what I have now
<div class="content">
<?php $query2 = "SELECT * FROM " . $table; ?>
<div class="query-class">
<?php echo $query2; ?>
</div>
<h1>
Tables In <?php echo $db; ?>
</h1>
<table>
<?php
$columquery = "SHOW COLUMNS FROM " . $table;
$columresult = mysql_query($columquery);
while ($row3 = mysql_fetch_array($columresult)) {
echo "<th>" . $row3['Field'] . "</th>";
}
?>
<?php
$result2 = mysql_query($query2);
while ($row2 = mysql_fetch_array($result2)) {
foreach($row2 as $var) {
echo "<tr><td>" . $var . "</td></tr>";
}
}
?>
</table>
</div>
Yes yes, I know it's horrible.
The other answers use the mysqli API while you're using the older, no longer supported mysql API. I really recommend upgrading to either mysqli or PDO, but if you want to stay with mysql you can use the following solution:
<div class="content">
<?php $query2 = "SELECT * FROM " . $table; ?>
<div class="query-class">
<?php echo $query2; ?>
</div>
<h1>
Tables In <?php echo $db; ?>
</h1>
<table>
<?php
$shouldOutputHeaders = true;
$result2 = mysql_query($query2);
while ($row2 = mysql_fetch_assoc($result2)) {
if ($shouldOutputHeaders) {
echo "<tr>";
foreach (array_keys($row2) as $header) {
echo "<th>" . $header . "</th>";
}
echo "</tr>";
$shouldOutputHeaders = false;
}
echo "<tr>";
foreach ($row2 as $var) {
echo "<td>" . $var . "</td>";
}
echo "</tr>";
}
?>
</table>
</div>
If i understood you well, You need mysqli_fetch_row.
$q= "SELECT * FROM table";
$result = $mysqli->query($q)
while ($row = $result->fetch_row()) {
print ("$row[0], $row[1]);
}
I think you are looking for something very ugly like the following. I found it in the garbage. I am not responsable for any use of it:
<?php
$db=Db::getConnection(); // singleton
$this->var['result']=$db->query($_POST['query']);
if (isset($this->var['result'])) {
echo '<table cellpadding="5" cellspacing="2" border="1"><tbody>';
$titles=array_keys(#$this->var['result'][0]);
echo '<tr>';
foreach($titles as $title)
echo '<th>'.$title.'</th>';
echo '</tr>';
foreach($this->var['result'] as $row) {
echo '<tr>';
foreach($row as $cell) {
echo '<td>'.$cell.'</td>';
}
echo '</tr>';
}
echo '</tbody></table>';
}
?>
Db is an standard singleton that contains a mysqli private object.
query() contains something like
$sql = $this->mysqli->query($query);
$this->lastInsertId = $this->mysqli->insert_id;
$errno = $this->mysqli->connect_errno;
if ($errno === 0) {
if ($this->mysqli->field_count > 0) {
while ($row = $sql->fetch_assoc()) $response[] = $row;
return $response;
}else{
return true;
}
}
to create the "array of arrays" response. Suitable for the output you are looking for.
I've added some escaping and only queried the database when needed:
// Print table tags
echo "<table>";
// Print out records
$q = mysql_query("SELECT * FROM {$table};");
if($res = $result->fetch_all(MYSQLI_ASSOC)){
// Print out columns
$columns = array_keys($res[0]);
echo'<tr><th>'.implode('</th><th>', array_map('htmlspecialchars',$columns).'</th></tr>';
// Print out table data
echo'<tr><td>'.implode('</td><td>', array_map('htmlspecialchars',$res).'</td></tr>';
} else {
// IFF there is no data, print out columns
$q = mysql_query("SHOW COLUMNS FROM {$table};");
if($res = $result->fetch_all(MYSQLI_ASSOC)){
// Print columns
echo'<tr><th>'.implode('</th><th>', array_map('htmlspecialchars',$res).'</th></tr>';
}
}
echo '</table>';
Hope this helps,

While Loop entire select Tag

Is it possible to while loop an entire select tag to have multiple dropdown menus?
What I am trying to achieve is to have a column full of dropdown menus in a table.
This is what I have tried so far
<?php
$DNS_FROM = $DNS."_port-%";
$select = "SELECT * FROM `uplink_port_mapping` WHERE DNS_From LIKE '$DNS_FROM'";
$select1 = mysqli_query($conn, $select);
$select2 = "SELECT DNS_From FROM `uplink_port_mapping` WHERE DNS_From NOT LIKE '$DNS_FROM' AND DNS_To = ''";
$select3 = mysqli_query($conn, $select2);
while($uplink_from = mysqli_fetch_assoc($select1)){
echo "<tr>";
echo "<td>".$uplink_from['DNS_From']."</td>";
echo "<td>"."<select name = 'uplink_to' multiple='multiple'>
<option value = '".$uplink_from['DNS_To']."' selected='selected'>". $uplink_from['DNS_To']."</option>";
while ($uplink_to = mysqli_fetch_assoc($select3)){
echo "<option value='".$uplink_to['DNS_From']."'>".$uplink_to['DNS_From']."</option>";
}
echo"</select>";
echo"</td>";
echo"</tr>";
}
?>
How it is right now.
The reason for the second while loop only working once is, that mysqli_fetch_assoc($result) will leave the pointer of the $result recource at it's end.
So when you try to loop the second time, mysqli_fetch_assoc($result) will not return anything (cause it's at the end of the $result recource.
Two possibilites:
Reset the pointer to the beginning:
<?php
....
while($uplink_from = mysqli_fetch_assoc($select1)){
echo "<tr>";
echo "<td>".$uplink_from['DNS_From']."</td>";
echo "<td>"."<select name = 'uplink_to' multiple='multiple'>
<option value = '".$uplink_from['DNS_To']."' selected='selected'>". $uplink_from['DNS_To']."</option>";
// here's the change:
mysql_data_seek($select3, 0);
while ($uplink_to = mysqli_fetch_assoc($select3)){
echo "<option value='".$uplink_to['DNS_From']."'>".$uplink_to['DNS_From']."</option>";
}
echo"</select>";
echo"</td>";
echo"</tr>";
}
....
?>
Or - which I think is the better solution - store that data into an array first, and then walk through that array:
<?php
...
$select2 = "SELECT DNS_From FROM `uplink_port_mapping` WHERE DNS_From NOT LIKE '$DNS_FROM' AND DNS_To = ''";
$result2 = mysqli_query($conn, $select2);
$dns_from = Array();
while ($uplink_to = mysqli_fetch_assoc($select3)){
$dns_from[] = $uplink_to;
}
....
// inside your first while loop:
foreach($dns_from as $dns) {
echo "<option value='".$dns['DNS_From']."'>".$dns['DNS_From']."</option>";
}
....
// note that I left out a bunch of your code, that doesn't change.
?>
Multiple select dropdown basic examples
$array = [
'Apple' => 1,
'Orange' => 0,
'Banana' => 1,
];
echo '<select multiple>';
foreach ($array as $fruit => $sel) {
$selected = 0;
if ($sel == 1) {
$selected = 'selected';
}
echo '<option value="' . $fruit . ' " ' . $selected . '>' . $fruit . '</option>';
}
echo '</select>';

How to set the selected option

I'm trying to get selected option in select,I need to make a select from my database and use id to mark which category is set.
echo"<select>";
while ($row = mysql_fetch_array($rezultat1))
{ if ($row['biljka_id']==$GET['b']) {
echo "<option value=".$row['biljka_id']." selected='selected' >".$row['naziv']."</option>";
} else { echo "<option value=".$row['biljka_id'].">".$row['naziv']."</option>";
}
echo"</select>";
Following is the short code.
You need not use if else statement as you need to justify only one variable depending upon condition.
You can do it with ternary operator.
<?php
echo "<select>";
while ($row = mysql_fetch_array($rezultat1)) {
$selected = ($row['biljka_id']==$GET['b']) ? 'selected="selected"' : '';
echo "<option value=".$row['biljka_id']. $selected ">".$row['naziv']."</option>";
}
echo"</select>";
?>
Rererence
You didn't properly close your while loop or the else part of your if, depending on how you look at it. Plus, why not use concatenation instead. So, you might re-write your code as follows:
$selectStr = '';
$selectStr .= "<select>";
while ($row = mysql_fetch_array($rezultat1))
{
if ($row['biljka_id']==$GET['b'])
{
$selectStr .= "<option value='".$row['biljka_id']."' selected='selected' >".$row['naziv']."</option>";
}
else
{
$selectStr .= "<option value='".$row['biljka_id']."'>". $row['naziv']. "</option>";
}
}
$selectStr .= "</select>";
echo $selectStr;

Selected value in a list

I'm trying to show the selected value in the list if it's found matching. It's successfully populated but the selected value code does not run.
Code:
$StaffName = 'Jimmy Chan';
<select name="Staff" id="Staff"><?php
$data = array();
$data[0] = '';
echo "<option value='" . $data[0] . "'>" . $data[0] . "</option>";
$result= $DB->query('select No, FirstName, LastName from Staff');
foreach ($result as $data)
{
$SNo = $data['No'];
$SFN = $data['FirstName'];
$SLN = $data['LastName'];
$SName = $SFN.' '.$SLN;
if($SName == $StaffName)
{
echo "<option value='".$Sno."' selected = \"selected\">".$Sname."</option>\n";
}
else
{
echo "<option value='" .$SNo. "'>" . $SName . " </option>";
}
}
?>
</select>
The second else statement do run but not the if statement. I have already put the "selected" inside. Kindly advise.
Try this:
foreach ($result as $data)
{
$SNo = $data['No'];
$SFN = $data['FirstName'];
$SLN = $data['LastName'];
$SName = trim($SFN).' '.trim($SLN);
if(strtolower($SName) == strtolower($StaffName))
{
echo "<option value='".$Sno."' selected = 'selected'>".$Sname."</option>\n";
}
else
{
echo "<option value='" .$SNo. "'>".$SName."</option>\n";
}
}
Also, you have $Sname instead of $SName in first "if" statement. I am not sure if PHP can make a difference on it, but just keep in mind.
The same for $Sno and $SNo variables.
It seems the problem is with the value in variable $SName. Before comparison trim and convert both variables to uppercase or lowercase.
Lower case: http://php.net/manual/en/function.strtolower.php
Uppercase: http://php.net/manual/en/function.strtoupper.php
Trim: http://php.net/manual/en/function.trim.php
Also try,
echo "<option value='".$Sno."' selected="selected">".$Sname."</option>"; //remove \n
You are using
echo "<option value='".$Sno."' selected = \"selected\">".$Sname."</option>\n";
But Variable names are $SNo and $SName and you are using $Sno and $Sname. So Please replace line with line given below.
echo "<option value='".$SNo."' selected = \"selected\">".$SName."</option>\n";
I hope i will be work for you,
thanks

How to make <option selected="selected"> set by MySQL and PHP?

How to make <option selected="selected"> set by MySQL and PHP?
My code:
echo '<select>';
$tempholder = array();
$rs = mysql_query("SELECT * FROM id ORDER BY year");
$nr = mysql_num_rows($rs);
for ($i=0; $i<$nr; $i++){
$r = mysql_fetch_array($rs);
//if($year==$r["year"]){ $selected=' selected="selected"'; }//doesn't work so
if (!in_array($r['year'], $tempholder)){
$tempholder[$i] = $r['year'];
echo "<option>".$r["year"]."</option>";//<option$selected>...
}
}
unset($tempholder);
echo '</select>';
Try this one:
echo '<select>';
$tempholder = array();
$rs = mysql_query("SELECT * FROM id ORDER BY year");
$nr = mysql_num_rows($rs);
for ($i=0; $i<$nr; $i++){
$r = mysql_fetch_array($rs);
if (!in_array($r['year'], $tempholder)){
$tempholder[$i] = $r['year'];
echo "<option".(($year==$r["year"])? ' selected="selected"' : '').">".$r["year"]."</option>";
}
}
unset($tempholder);
echo '</select>';
It doesn't saves the state in a variable which you have to overwrite.
And I think the real error was the single equal sign in $year=$r["year"] and not wihtin the rest of the code.
In addition to fixing the =/== gotcha, you can save yourself the array lookup and make the code simpler by asking the database to return each year only once in the query:
<select>
<?php $result= mysql_query('SELECT DISTINCT year FROM id ORDER BY year'); ?>
<?php while($row= mysql_fetch_assoc($result)) { ?>
<option <?php if ($row['year']==$year) { ?>selected="selected"<?php } ?>>
<?php echo htmlspecialchars($row['year']); ?>
</option>
<?php } ?>
</select>
(You may not need htmlspecialchars() assuming that's a numeric year, but it's good practice always to HTML-escape any plain text you include in an HTML template. You can define a function with a shorter name to do the echo htmlspecialchars to cut down on typing.
)
You must define $selected everytime, and you were using the assignment operator instead of the comparison:
echo '<select>';
$tempholder = array();
$rs = mysql_query("SELECT * FROM id ORDER BY year");
$nr = mysql_num_rows($rs);
for ($i = 0; $i < $nr; $i++){
if($year == $r["year"]) { //not $year = $r["year"]
$selected=' selected="selected"';
}
else {
$selected = "";
}
$r = mysql_fetch_array($rs);
if (!in_array($r['year'], $tempholder)){
$tempholder[$i] = $r['year'];
echo "<option$selected>" . $r["year"] . "</option>";
}
}
unset($tempholder);
echo '</select>';
Adding a new answer here for posterity, since the old code, which while correct at the time (actually mysqli did exist, but many hosts didn't support PHP 5), is unfortunately using deprecated code. Instead of using mysql_ extensions, here's a way to handle it using an object oriented approach which will work with mysqli_ connections:
Here's the database connection
$conn = new mysqli($host, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Assuming that the $year variable is coming from a form (though it could be used from GET or SESSION or wherever)
$year = $_POST['year'];
Here's the query for the option button (I have it broken out into different rows to make it a little easier to read):
$result=$conn->query($sql);
while($row = $result->fetch_assoc()) {
if ($row['year']==$year) {
$selected = 'selected="selected"';
}
else {
$selected = '';
}
echo '<option value="'.$row['year'].'" '. $selected . '>"'
. $row['year'] .'</option>';
}

Categories