I want to fetch a table which has 2 columns: id and name,
and I want column id as value for each option, and column name as option name
This is my controller
//populate provinsi
$this->load->model('Provinsi');
$provinsi = $this->Provinsi->get();
$this->load->view('admin/pages/product_form', array(
'provinces' => $provinsi,
));
And in my view
<?php
$options_provinsi = array('select_one' => 'Select one');
foreach ($provinces as $provinsi) {
$options_provinsi[] = array(
$provinsi->id => $provinsi->nama,
);
}
$extra = 'id="provinsi" class="form-control" onChange="loadLocation('provinsi','kota');"';
echo form_dropdown('provinsi', $options_provinsi, 'select_one', $extra);
?>
This code meet my needs, but because I use array, the dropdown become like this:
How to set option value without using an array?
replace your foreach loop
foreach ($provinces as $provinsi) {
$options_provinsi[$provinsi->id] = $provinsi->nama;
}
and in view
$extra = null;
echo form_dropdown('provinsi', $options_provinsi, 'select_one', $extra);
Put This :
$extra_string = null;
foreach($extra as $key => $value) {
$extra_string .= " {$key}='{$value}'";
}
And change last line to be:
echo form_dropdown('provinsi', $options_provinsi, 'select_one', $extra_string);
As you can see checking codeigniter docs you will find out that extra param should be string not an array.
If it it's an array then form_dropdown() will produce an with the array key as the label.
Related
I have 3 input that can be added dynamically. So the name of input is array, like:
<input type="text" name="qty1[]">
<input type="text" name="qty2[]">
<input type="text" name="qty3[]">
(Each of these input texts can be generated by javascript)
In my php file, I get them and want to insert to database (my controller in codeigniter):
$address = $this->input->post("qty1");
$LocX = $this->input->post("qty2");
$LocY = $this->input->post("qty3");
In my db part, where I want to use foreach and add to database:
Edit
foreach ($address as $key) {
// I want to add $LocX and $LocY to the table
// LocX and LocY are column names.
$query = $this->db->query("INSERT INTO address (Comp_ID, Value, LocX, LocY)
VALUES(?, ?)", array($Comp_ID, $key ,? ,?));
}
I want to add all of them into foreach as parameter. As I searched it's not possible. What shoud I do? Thanks.
Edit2
The result of arrays, for example for $LocX :
Array
(
[0] => test1
[1] => test2
[2] => test3
)
You can use the index in the foreach to get to the other elements. But you need to carefully check if the index value exists in the other arrays (isset check)
For example:
foreach ($address as $key => $value) {
if(isset($LocX[$key], $LocY[$key]) {
$a_LocX = $LocX[$key]; // This will be the locx of the address
$a_LocY = $LocY[$key]; // This will be the locy of the address
// Change your query to fit the table and fill in the locx and y.
$query = $this->db->query("INSERT INTO address (Comp_ID, Value)
VALUES(?, ?)", array($Comp_ID, $key));
}
You can also use a for loop for this.
$address = $this->input->post("qty1");
$LocX = $this->input->post("qty2");
$LocY = $this->input->post("qty3");
$n=count($address);
for($i=0;$i<$n;$i++){
$a=$address[$i];
$x=$locX[$i];
$y=$locY[$i];
//insert here
}
I will suggest you to use Codeigniter syntax, and this will make your insert work,
foreach($address as $k => $v)
{
$insert = array(
'Comp_ID' => $Comp_ID,
'Value' => $v,
); // insert array
if(in_array($LocX[$k], $LocX)) // existance check
$insert = array_merge($insert, array('LocX' => $LocX[$k]));
if(in_array($LocY[$k], $LocY)) // existance check
$insert = array_merge($insert, array('LocY' => $LocY[$k]));
$this->db->insert('address', $insert); // No need to write full query
}
I want to eliminate all the duplicates in a select dropdown list created with PHP.
My PHP code that creates the dropdown list is the following:
public static function getDropdownlist($conn)
{
//Initialize dropdown list
//--------------------------------------------------
$ddl_query = "select * from MIS_EMPLOYEES";
$stmt_ddl = oci_parse($conn, $ddl_query);
oci_execute($stmt_ddl);
//A default value -- this will be the selected item in the dropdown ##
$prosopiko = JRequest::getVar('bodies', 0);
if ($prosopiko == 0)
$default = 0;
else
$default = $prosopiko;
//Initialize array to store dropdown options ##
$options = array();
// $options = array_unique();
$options[] = JHTML::_('select.option', '0', 'Επιλέξτε');
while (($row = oci_fetch_array($stmt_ddl, OCI_ASSOC+OCI_RETURN_NULLS)) != false) {
$options[] = JHTML::_('select.option', $row['ID'], $row['POSITION']);
}
//Create <select name="month" class="inputbox"></select> ##
$dropdown = JHTML::_('select.genericlist', $options, 'bodies', 'class="inputbox"', 'value', 'text', $default);
return $dropdown;
}
}
But it brings all the duplicates written from an Oracle table.
How can I eliminate the duplicates? I tried array_unique but I failed.
In your SQL statement, simply change it to gather distinct elements you are interested in.
Since you are only using two values in the above code for the value and text, something like this should work:
SELECT ID, POSITION
FROM MIS_EMPLOYEES
GROUP BY ID, POSITION
Easiest option is to modify your query to SELECT DISTINCT ID, POSITION or GROUP BY ID, POSITION. Other than that you'll need to build up an array and use array_unique on that.
I'm trying to get some specific keys and values from the database. My database entries look like so:
id | name | description | value
------------------------------------------
1 | lang | default language | en
2 | date | date format | YYYY-MM-DD
I want to echo only my name and value fields. I've tried using a nested foreach loop, like so:
foreach($details as $key => $value)
{
foreach($value as $index => $row)
{
echo $index . " / " . $row . "<br />";
}
echo "<br />";
}
But that only echos:
id / 1
name / lang
description / default language
value / en
id / 2
name / date
description / date format
value / YYYY-MM-DD
However, when I add an offset, like so: $index[1], I get this like a instead of name, or e instead of description.
I've previously worked from while loops using mysql_fetch_array, but this would give me a repeated element (say a <tr>) whereas I simply need to extract the value of the field because this will be used to build a form for the user to manage.
Would anyone have a suggestion or different approach for me to do something of the sort ?
EDIT
The query comes from a class file:
// extracted from my queries.class.php
public function my_prefs()
{
global $db;
$query = "SELECT * FROM preferences WHERE value!=NULL";
return $db->select($query);
}
// extracted from the source file
$module_details = $query->my_prefs();
EDIT #2
Perhaps this will help you understand my needs:
foreach($module_details as $key => $value)
{
print_r($module_details);
}
returns:
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => lang
[description] => default language
[value] => en
)
[1] => stdClass Object
(
[id] => 1
[name] => date
[description] => date format
[value] => YYYY-MM-DD
)
}
I need to access only lang / en and date / YYYY-MM-DD.
Sounds like you're looking for something like this:
$tmp = array();
foreach($details as $key => $value)
{
// "name" => "value" dictionary later access
$tmp[$value["name"]] = $value["value"];
echo $value["name"] . " = " . $value["name"]; // echos e.q. "date = YYYY-MM-DD"
echo "<br/>";
}
echo $tmp["date"]; // echos e.q. "YYYY-MM-DD"
Perhaps I misunderstood the question..
But I believe you are trying to access the specific column entry from the array. You can do this by using the keys you are outputting instead of using a numeric index.
foreach($details as $key => $value)
{
echo $value['name'];
echo $value['value'];
echo "<br />";
}
EDIT
If you want to limit the results from your query so you only have the fields you requested replace:
$query = "SELECT * FROM preferences WHERE value!=NULL";
with
$query = "SELECT name, value FROM preferences WHERE value!=NULL";
Finally got around to getting something to work. Here's what I did:
foreach($details as $row)
{
$name = $row->name;
$value = $row->value;
// In order to specify for checkboxes, select, radio, etc.
if($name == "lang")
{
// different info depending on the value
}
else
{
// do something generic here
}
}
Might not be an optimal option, but this works like I need it to work.
i am tying to do this by a function. i want every item found in the db to be echoed out as a list
eg. item1
item2
item3
item4
i know im missing something but it is puzzling me. for now im only seeing one list and upon
refresh another item shows up replacing the other. plz help and thanks
function get_list() {
$id = mysql_real_escape_string(#$_GET['id']);
$get_list = array();
$bar = mysql_query(" SELECT bar.* FROM bar WHERE bar.b_id = '$id' ORDER BY rand()");
while($kpl = mysql_fetch_assoc($bar)){
$get_list[] = array( 'videoid' => $kpl['videoid'],
'name' => $kpl['name'],
'description' => $kpl['description'],
'type' => $kpl['type'],
'bev' => $kpl['bev'],
);
}
foreach ($get_list as $get_list);
return $get_list;
}
?>
<?php
$gkp_list = gkp_list();
foreach ($gkp_list as $gkp_list);
if (empty($gkp_list)){ echo 'no video'; }
else {
echo '<p>$gkp_list['name']. '<br/></p>';}
?>
There are some major syntax problems there.
function get_list() {
$id = mysql_real_escape_string(#$_GET['id']);
$get_list = array();
$bar = mysql_query(" SELECT bar.* FROM bar WHERE bar.b_id = '$id' ORDER BY rand()");
while($kpl = mysql_fetch_assoc($bar)){
$get_list[] = $kpl;
}
return $get_list;
}
$gkp_list = get_list();
if (empty($gkp_list)) {
echo 'no video';
} else {
foreach ($gkp_list as $gkp_item) {
echo '<p>' . $gkp_item['name']. '<br/></p>';
}
}
?>
The purpose of foreach is to loop over an array and do something with each value. Don't use foreach if you're working with the array as a whole (in this case, returning it)
Foreach doesn't have a semicolon at the end, it typically has an opening curly brace ({).
You don't need to manually copy all of the array indexes in the while loop, because all of the indexes are the same.
The string for the output was formatted wrong, you have to be careful. Use a syntax-highlighting editor.
The two variable names in foreach must be different. One refers to the array, and one refers to the value of that key.
I have an array like this:
$tset = "MAIN_TEST_SET";
$gettc = "101";
$getbid = "b12";
$getresultsid = "4587879";
$users["$tset"] = array(
"testcase"=>"$gettc",
"buildid"=>"$getbid",
"resultsid"=>"$getresultsid"
);
Arrays in PHP is confusing me.
I want to display some like this:
MAIN_TEST_SET
101 b12 4587879
102 b13 4546464
103 b14 5545465
MAIN_TEST_SET3
201 n12 45454464
MAIN_TEST_SET4
302 k32 36545445
How to display this?
Thanks.
print_r($users)
That will print your array out recursively in an intuitive way. See the manual: http://us2.php.net/manual/en/function.print-r.php
If you want to print it in the specific way you formatted it above you're going to have to write a custom function that uses foreach looping syntax like this:
<?php
echo "<table>";
foreach($users as $testSetName=>$arrayOfTestCases){
echo "<tr><td>".$testSetName."</td></tr>";
foreach($arrayOfTestCases as $k=>$arrayOfTestCaseFields){
//$arrayOfTestCaseFields should be an array of test case data associated with $testSetName
$i = 0;
foreach($arrayOfTestCaseFields as $fieldName => $fieldValue){
//$fieldValue is a field of a testcase $arrayOfTestCaseFields
if($i == 0){
//inject a blank table cell at the beginning of each test case row.
echo "<tr><td> </td>";
$i++;
}
echo "<td>".$fieldValue."</td>";
}
echo "</tr>";
}
}
echo "</table>";
?>
Your data should be composed as follows:
$tset = "MAIN_TEST_SET";
$gettc = "101";
$getbid = "b12";
$getresultsid = "4587879";
$users[$tset] = array();
$users[$tset][] = array( "testcase"=>"$gettc",
"buildid"=>"$getbid",
"resultsid"=>"$getresultsid"
);
$users[$tset][] = ... and so forth ...
To fix the data structure you present (as Victor Nicollet mentions in his comment) you need something like this:
$users = array(); // Create an empty array for the users? (Maybe testsets is a better name?)
$testset = array(); // Create an empty array for the first testset
// Add the test details to the testset (array_push adds an item (an array containing the results in this case) to the end of the array)
array_push($testset, array("testcase"=>"101", "buildid"=>"b12", "resultsid" => "4587879"));
array_push($testset, array("testcase"=>"102", "buildid"=>"b13", "resultsid" => "4546464"));
// etc
// Add the testset array to the users array with a named key
$users['MAIN_TEST_SET'] = $testset;
// Repeat for the other testsets
$testset = array(); // Create an empty array for the second testset
// etc
Of course there are much more methods of creating your data structure, but this one seems/looks the most clear I can think of.
Use something like this to create a HTML table using the data structure described above.
echo "<table>\n";
foreach($users as $tsetname => $tset)
{
echo '<tr><td colspan="3">'.$tsetname.'</td></tr>\n';
foreach($tset as $test)
echo "<tr><td>".$test['testcase']."</td><td>".$test['buildid']."</td><td>".$test['resultsid']."</td></tr>\n";
}
echo "</table>\n";
The first foreach iterates over your test sets and the second one iterates over the tests in a test set.
For a short uncustomisable output, you can use:
print_r($users)
alternatively, you can use nested loops.
foreach($users as $key => $user) {
echo $key . "<br />"
echo $user["testcase"] . " " . $user["buildid"] . " " . $user["resultsid"];
}
If you are not outputting to html, replace the <br /> with "\n"