I get some values from an old db of a client as such:
$query = "SELECT rowid,source FROM `".$table."`";
$result = mysql_query($query);$temp=0;$p = array();
while ($row = mysql_fetch_array($result)) {$p[$temp] = $row;$temp++;}
and then I loop through the values as such:
// loop through all possible values
foreach ($p as $obj) {
}
Inside the foreach loop I will print <option> element and I want to determine the <option selected/> elements. The selected elements could be more than 1, since its a multiselect form.
First thing I check whether a $selected value equals to rowid.
// check if exists equals to rowid
if ($obj["rowid"] == $selected){
$return .= '<option value="'.$obj["rowid"].'" selected>'.$obj["source"].'</option>';
}else{
$return .= '<option value="'.$obj["rowid"].'">'.$obj["source"].'</option>';
}
This works just find if $selected = "1" (or any single digit)
My problem and my question comes if $selected = "3,4". Then I need to loop through the values and separate the comma-separated values inside foreach ?
Here is my complete code:
$selected = "3,4";
$query = "SELECT rowid,source FROM `" . $table . "`";
$result = mysql_query($query);
$temp = 0;
$p = array();
while ($row = mysql_fetch_array($result)) {
$p[$temp] = $row;
$temp++;
}
// loop through all possible values
foreach($p as $obj) {
// check if exists equals to rowid
if ($obj["rowid"] == $selected) {
$return.= '<option value="' . $obj["rowid"] . '" selected>' . $obj["source"] . '</option>';
}
else {
// check if default exists with comma separated values
if (!empty($default) && strpos($selected, ',') !== false) {
$arr_values = explode(',', $selected);
// loop through comma-separated values to get the selected items
foreach($arr_values as $selected) {
if ($obj["rowid"] == $default) {
$return.= '<option value="' . $obj["rowid"] . '" selected>' . $obj["source"] . '</option>';
}
}
// $return .= '<option value="'.$obj["rowid"].'">'.$obj["source"].'</option>';
}
else {
$return.= '<option value="' . $obj["rowid"] . '">' . $obj["source"] . '</option>';
}
}
}
Just use in_array() + explode() functions combination to check if rowid exists in selected string
if (in_array ($obj["rowid"], explode(",",$selected))){
$return .= '<option value="'.$obj["rowid"].'" selected>'.$obj["source"].'</option>';
}else{
$return .= '<option value="'.$obj["rowid"].'">'.$obj["source"].'</option>';
}
Explanation: E.G. if $selected = "3,4" then explode(",",$selected) return you array(3,4) and in_array check if $obj["rowid"]' exists in that array so it mean you will have in you output multiple <options with attribute selected set
Related
I need help with this. I must pass a PHP MySQL function to CodeIgniter, but it does not show me the data, it stops right in if(array_key_exists($pos, $rs))
Does the query well but does not enter the conditional if
Any solution?
This is my Code in CodeIgniter
public function table($hour, $row)
{
global $rs;
if ($rs === null)
{
$this->db->select("CONCAT(t.tbl_row, '_', t.tbl_col) as pos, t.tbl_id, t.sub_id, s.sub_name", false);
$this->db->join('redips_timetable AS t', 't.sub_id = s.sub_id');
$rs = $this->db->get('redips_subject AS s')->result();
}
echo '<tr>';
echo '<td class="mark dark">' . $hour . '</td>';
for ($col = 1; $col <= 5; $col++)
{
echo '<td>';
$pos = $row . '_' . $col;
if(array_key_exists($pos, $rs))
{
$elements = $rs[$pos];
$id = $elements['sub_id'] . 'b' . $elements['tbl_id'];
$name = $elements['sub_name'];
$class = substr($id, 0, 2);
echo "<div id=\"$id\" class=\"redips-drag $class\">$name</div>";
}
echo '</td>';
}
echo "</tr>\n";
}
Original MySQL code
function table($hour, $row) {
global $rs;
// if $rs is null then query database (this should be executed only once - first time)
if ($rs === null)
{
// first column of the query is used as key in returned array
$rs = sqlQuery("select concat(t.tbl_row,'_',t.tbl_col) as pos, t.tbl_id, t.sub_id, s.sub_name
from redips_timetable t, redips_subject s
where t.sub_id = s.sub_id", 0);
}
print '<tr>';
print '<td class="mark dark">' . $hour . '</td>';
// column loop starts from 1 because column 0 is for hours
for ($col = 1; $col <= 5; $col++) {
// create table cell
print '<td>';
// prepare position key in the same way as the array key looks
$pos = $row . '_' . $col;
// if content for the current table cell exists
if (array_key_exists($pos, $rs)) {
// prepare elements for defined position (it can be more than one element per table cell)
$elements = $rs[$pos];
// id of DIV element will start with sub_id and followed with 'b' (because cloned elements on the page have 'c') and with tbl_id
// this way content from the database will not be in collision with new content dragged from the left table and each id stays unique
$id = $elements[2] . 'b' . $elements[1];
$name = $elements[3];
$class = substr($id, 0, 2); // class name is only first 2 letters from ID
print "<div id=\"$id\" class=\"redips-drag $class\">$name</div>";
}
// close table cell
print '</td>';
}
print "</tr>\n";
}
/*
if you need find array key
you got object in $rs varible
( $rs = $this->db->get('redips_subject AS s')->result(); )
so need convert obj to array in for each loop
*/
public function table($hour, $row)
{
global $rs;
if ($rs === null)
{
$this->db->select("CONCAT(t.tbl_row, '_', t.tbl_col) as pos, t.tbl_id, t.sub_id, s.sub_name", false);
$this->db->join('redips_timetable AS t', 't.sub_id = s.sub_id');
$rs = $this->db->get('redips_subject AS s')->result();
}
echo '<tr>';
echo '<td class="mark dark">' . $hour . '</td>';
for ($col = 1; $col <= 5; $col++)
{
$arr = get_object_vars($rs[$col]);
echo '<td>';
$pos = $row . '_' . $col;
if(array_key_exists($pos, $arr))
{
$elements = $arr[$pos];
$id = $elements['sub_id'] . 'b' . $elements['tbl_id'];
$name = $elements['sub_name'];
$class = substr($id, 0, 2);
echo "<div id=\"$id\" class=\"redips-drag $class\">$name</div>";
}
echo '</td>';
}
echo "</tr>\n";
}
I just copy and paste, and then modify the code, it works fine to build a select.
$sql_company_list = "SELECT Company FROM company_view";
$data = $db->build_select($sql_company_list);
public function build_select($sql){
$data = $this->db->prepare($sql);
$data->execute();
$data->setFetchMode(PDO::FETCH_ASSOC);
$option = "";
$count = 1;
foreach($data as $row){
foreach ($row as $name=>$value){
$option .= "<option value=".$count;
$option .= ">";
$option .= "".$value."";
$option .= "</option>";
}
$count++;
}
return $option;
}
But, when I wish to select id and company as option value (id) and option name (company), it don't work. How to make minimal changes to do it? Many thanks.
$sql_company_list = "SELECT id, Company FROM company_view";
$data = $db->build_select_1($sql_company_list);
public function build_select_1($sql){
$data = $this->db->prepare($sql);
$data->execute();
$data->setFetchMode(PDO::FETCH_ASSOC); // i don't exactly understand...
$option = "";
//$count = 1;
foreach($data as $row){
foreach ($row){ // this don't work
$option .= "<option value=".$row[0];
// i wish to do this e.g. value assigns to ID
$option .= ">";
$option .= "".$row[1]."";
// i wish to do this e.g. option name assigns to company
$option .= "</option>";
}
//$count++;
}
return $option;
}
As per your working code,
foreach ($row as $name=>$value){
$option .= "<option value=".$count;
$option .= ">";
$option .= "".$value."";
$option .= "</option>";
}
This is working correctly for you. So for setting name and value of company to dropdown options, you can modify your code as below.
Instead of $row[0] and $row[1], use it the below way
foreach ($row as $name=>$value){
$option .= "<option value=".$value;
$option .= ">";
$option .= "".$name."";
$option .= "</option>";
}
Try it and see if it works for you.
In my code I am using PHP which populates the bootstrap multi selectpicker from MySQL database but the problem is it only selects the last option instead of multiple options, I don't know what I am missing in it? Here is my my code
function MultiBindCombo($tablenames, $columnnames1, $columnnames2, $comboname, $selectedopt) {
global $conn;
$sql="SELECT ". $columnnames1. ", " . $columnnames2 . " FROM ". $tablenames;
$result = mysqli_query($conn, $sql);
if( ! $result ) {
echo mysql_error();
exit;
}
echo '<select class="selectpicker form-control" data-live-search="true" name="' . $comboname . '" multiple="multiple">';
$array = explode(',', $selectedopt);
while ($row=mysqli_fetch_array($result)) {
foreach ($array as $select_option){
if($row[$columnnames1] == $select_option) {
$print_selected = 'selected';
} else {
$print_selected = '';
}
echo $select_option;
}
echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>';
}
echo '</select>';
}
To get all selected values in a multiselect you need to use name attribute with []:
echo '<select class="selectpicker form-control" data-live-search="true" name="' . $comboname . '[]" multiple="multiple">';
After that you can iterate over $_POST[$comboname] with a foreach.
Update:
Let's look closer to your code here:
while ($row=mysqli_fetch_array($result)) {
foreach ($array as $select_option){
// You iterate over every value of array, so in the end
// `$print_selected` is defined depending on value of the
// last `$select_option`
if($row[$columnnames1] == $select_option) {
$print_selected = 'selected';
} else {
$print_selected = '';
}
// remove this. Why you echo `$select_option`?
echo $select_option;
}
echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>';
}
Rewrite it as:
while ($row=mysqli_fetch_array($result)) {
$print_selected = '';
foreach ($array as $select_option){
if($row[$columnnames1] == $select_option) {
$print_selected = 'selected';
// break `foreach` as you found the right item
break;
}
}
// if right item is not found - `$print_selected` is empty
echo '<option data-tokens="' . $row[$columnnames1] . '" value="' . $row[$columnnames1] . '"' .$print_selected. '>' . $row[$columnnames2] . '</option>';
}
I have a html-form to read out data from an SQL-database. The number of selections is completely free, which means that there are no obligatory fields.
I would like to show the results that meet all selected criteria in a html-table. Here is my code:
<?php
include("../files/zugriff.inc.php");
if (isset($_POST["submit"])) {
$sent = $_POST['sent'];
$datenWerte = array();
$fruitname = $_POST["fruitname"];
$fruitgroup = $_POST["fruitgroup"];
$vegetablegroup = $_POST["vegetablegroup"];
$country = $_POST["country"];
$season = $_POST["season"];
$diameter = $_POST["diameter"];
$color = $_POST["color"];
if(!empty($fruitgroup)) {
$datenWerte['fruitgroup'] = $fruitgroup;
}
if(!empty($vegetablegroup)) {
$datenWerte['vegetablegroup'] = $vegetablegroup;
}
if(!empty($country)) {
$datenWerte['country'] = $country;
}
if(!empty($season)) {
$datenWerte['season'] = $season;
}
if(!empty($diameter)) {
$datenWerte['diameter'] = $diameter;
}
if(!empty($color)) {
$datenWerte['color '] = $color;
}
foreach ($datenWerte as $key => $value) {
$spalten[] = $key;
$werte[] = "'$value'";
}
echo "<b>Results:</b><br><br>";
$sql = "SELECT * FROM fruitdatabase WHERE (" . implode(", ",
$spalten) . ") = (" . implode(", ", $werte) . ")";
$result = mysqli_query($db, $sql);
$data = array();
while($row = $result->fetch_object()){
$data[] = $row;
}
// Numeric array with data that will be displayed in HTML table
$aray = $data;
$nr_elm = count($aray); // gets number of elements in $aray
// Create the beginning of HTML table, and of the first row
$html_table = '<table border="1 cellspacing="0" cellpadding="2""><tr>';
$nr_col = count($spalten); // Sets the number of columns
// If the array has elements
if ($nr_elm > 0) {
// Traverse the array with FOR
for($i=0; $i<$nr_elm; $i++) {
$html_table .= '<td>' .$aray[$i]. '</td>'; // adds the value in
column in table
// If the number of columns is completed for a row (rest of
division of ($i + 1) to $nr_col is 0)
// Closes the current row, and begins another row
$col_to_add = ($i+1) % $nr_col;
if($col_to_add == 0) { $html_table .= '</tr><tr>'; }
}
// Adds empty column if the current row is not completed
if($col_to_add != 0) $html_table .= '<td colspan="'. ($nr_col -
$col_to_add). '"> </td>';
}
$html_table .= '</tr></table>'; // ends the last row, and the table
// Delete posible empty row (<tr></tr>) which cand be created after last
column
$html_table = str_replace('<tr></tr>', '', $html_table);
echo $html_table; // display the HTML table
}
mysqli_close($db);
?>
Unfortunately, it´s not working. Could somebody please help me to find the error?
Than you very much in advance!
I want to create dynamic select lists. For example: I have 5 students in my db. My goal is to create 5 selects ,and in every select all students which are in database. So if user inserts a 6th student in the database, the page should display 6 selects, and in every select names of 6 students.
I've tried with this code, but it only creates 1 select, containing 4 students(the first one from the db is missing).
The Code:
$con=mysqli_connect("localhost","root","","novi-studomat");
$exe="SELECT * FROM kolegij WHERE id_student='$id_student'";
$i=1;
$execute=mysqli_query($con,$exe);
while($result=mysqli_fetch_array($execute))
{
echo '<select name=student'.$i.'>';
echo '<option value="-1" >Choose student</option> <br/>';
while($res=mysqli_fetch_array($execute))
{
echo '<option value='.$res["id_student"].'>'.$res["name"].'</option> <br/>';
}
echo '</select>';
$i++;
}
$con=mysqli_connect("localhost","root","","novi-studomat");
$exe="SELECT * FROM kolegij WHERE id_student='$id_student'";
$i=1;
$execute=mysqli_query($con,$exe);
$select = '';
for($j = 0; $j < mysqli_num_rows($execute); $j++) {
$select .= '<select name=student' . $j . '>';
$select .= '<option value="-1" >Choose student</option> <br/>';
while($result=mysqli_fetch_array($execute)) {
$select .= '<option value=' . $res["id_student"].'>' . $res["name"] . '</option>';
$i++;
}
$select .= '</select>';
}
echo $select;
UPDATE
inside the while
$select = '<select name=student' . $j . '>';
$select .= '<option value=' . $res["id_student"].'>' . $res["name"] .
change this lines by this other
$select = '<select name="student' . $j . '">';
$select .= '<option value="' . $res["id_student"]."'>' . $res["name"] .
we missed the double quotes for value and in select name
Problem solved, I just needed to insert vars $exe and $execute inside for loop, so after every iteration $result is refreshed,otherwise it just prints options in first select...
CODE:
$con=mysqli_connect("localhost","root","","novi-studomat");
$exe="SELECT * FROM kolegij WHERE id_student='$id_student'";
$execute=mysqli_query($con,$exe);
$select = '';
for($j = 0; $j < mysqli_num_rows($execute); $j++)
{
$exe="SELECT * FROM kolegij WHERE id_student='$id_student'";
$execute=mysqli_query($con,$exe);
$select .= '<select name=student' . $j . '>';
$select .= '<option value="-1" >Choose student</option> <br/>';
while($result=mysqli_fetch_array($execute))
{
$select .= '<option value=' . $res["id_student"].'>' . $res["name"] . '</option>';
}
$select .= '</select>';
}
echo $select;