get specific keys from database - php

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.

Related

How to add <hr> tags between unique rows from query resultset?

I'm trying to add an <hr> tag between lines when a new name is encountered.
$conn = new mysqli("localhost", "root", "", "test");
$rs = $conn->query("SELECT * FROM usuarios");
$info = [];
$i = 0;
while($rows = $rs->fetch_array()) {
$info[$i]["pass"] = $rows["pass"];
$info[$i]["name"] = $rows["name_real"];
$i++;
}
// I want to print a line just after the last duplicated value
for($i = 0; $i < count($info) - 1; $i++) {
if($info[$i]["name"] !== $info[$i +1]["name"] && // some duplicate condition) {
$info[$i]["line"] = "<hr>";
};
}
This is the structure of my info array build from the resultset.
Array
(
[0] => Array
(
[pass] => 12
[name] => Martin
)
[1] => Array
(
[pass] => 20
[name] => Martin
)
[2] => Array
(
[pass] => 2
[name] => Martin
)
[3] => Array
(
[pass] => 2
[name] => Alberto
)
)
My desired result would be something like:
<p>Martin<p>
<p>Martin<p>
<p>Martin<p>
<hr>
<p>Alberto<p>
If you don't care what the duplicate names are or how many duplicates exist, and you just want to see whether or not there are any, it looks like it could be simpler code than some of the possible duplicate answers.
Get the names
$names = array_column($array, 'name');
Then check if the full list of names is equal to the unique list.
$has_duplicates = $names != array_unique($names);
Disclaimer: This answer looks odd now. It was provided for Revision 1 of the question. I seem to have misunderstood the question somewhat, and then Revision 2 transformed it to the extent that this answer no longer applies at all. Still, I think it's a useful way to do the thing that it seemed was trying to be done at first.
This solution would be handy:
$result = array();
$names = array_count_values(array_column($source, 'name'));
foreach($names as $key=>$val) {
$result[$key] = ($val == 1 ? false : true);
}
This can be achieved with just one loop. First, use your mysqli query to order the resultset by name_real. (If you are only going to use name_real, you can change the SELECT clause to reflect this. I have shown this in the commented query.) Then write a condition that checks for a new/unique name_real -- if so, echo <hr>.
Code: (Demo)
//$rs = $conn->query("SELECT `name_real` FROM usuarios ORDER BY `name_real`;");
$rs=[
['pass'=>2,'name_real'=>'Alberto'],
['pass'=>12,'name_real'=>'Martin'],
['pass'=>20,'name_real'=>'Martin'],
['pass'=>2,'name_real'=>'Martin']
];
$prev=NULL;
//while($rows = $rs->fetch_array()) {
foreach($rs as $rows){
if($prev && $rows['name_real']!=$prev){ // if not first iteration, and new name_real
echo "<hr>";
}
echo "<p>{$rows['name_real']}</p>";
$prev=$rows['name_real']; // preserve this value for next iteration's check
}
Output:
<p>Alberto</p>
<hr>
<p>Martin</p>
<p>Martin</p>
<p>Martin</p>

loop repeating comparing arrays

I have this code and I want to compare the data that came from db with the one user selects but it seems that the foreach($question_answers as $answer){
and foreach ($user_answer as $key => $value) { it is not good it is repeating for 4 times more, I need a way to compare $user_answer which is what user has selected request from the view, and the $answer['order'] the order comes from database. So I need a loop or something to compare these two.. any help..? thank you.
foreach($questions as $question) {
$question_answers = OrderingAnswer::where('question_id', $question->id)
->where('deleted',0)
->get()
->toArray();
$users_answers = $request->except('_token', 'test_id');
$user_answer = $users_answers[ $question->id];
// $user_answer ---> Array ( [0] => 1 [1] => 4 [2] => 3 [3] => 2 )
foreach ($question_answers as $answer) {
//$answer['order'] ---> 1
foreach ($user_answer as $key => $value) {
if ($answer['order'] == $value ) {
echo "ok ===>" .$value . "<br>" ;
} else {
echo "no -------------------------------- >".$value . "<br>" ;
}
}
}
I have tried this - it is working perfect. (This question was really intresting)
Here basically i am comparing multidimensional array value to a single dimensional array value. it will just give you array of matched results.
<?php
$question_answers= array(
array("id"=>251,'question_id'=>242,'order'=>1),
array("id"=>252,'question_id'=>243,'order'=>2)
);
$user_answers = array(1,4,3,2);
// you can just use this part
$question_answers = array_filter($question_answers, function($arr) use ($user_answers) {
return in_array($arr['order'], $user_answers);
});
echo "<pre>";
print_r($question_answers);
?>

codeigniter form_dropdown, set option value without an array

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.

PHP Multidimensional Array or better option?

I have a code that takes posted data from form A and then find the prices of goods and display them. Now i need to do more with the following data in the body of the 2nd form:
Item name
Item Qty
Item Price
The code is here:
<?php
echo "<div style='width:30%; height:auto; border: 2px solid;'>";
echo "<h1>The Items Are...</h1><br>";
//array that will hold the sum of each item cost
$totalAmountArray = array();
foreach ($_POST['basket'] as $name => $value)
{
//indexer for totalAmountArray
$i=0;
if($value > 0){
//echo $name . ": " . $value . "<br>";
$itemPrice;
//reassign
$itemName = $name;
$itemQty = $value;
//sql connection..
mysql_connect();
mysql_select_db("xxxxxx");
$result = mysql_query("SELECT * FROM pricing WHERE item = '".$name."'");
while($row = mysql_fetch_array($result)){
$itemPrice = $row['price'];
/*DEBUGGING*/
echo "Item Name: <b>".$itemName . " </b># ";
echo "<b>".$itemPrice ." </b>X ".$itemQty."<br>";
}//end of while loop
//multiply to get total for this item - store in temp
$temp = $itemQty * $itemPrice;
//store temp at index i in totalAmountArray
array_push($totalAmountArray, $temp);
unset($result);
unset($itemPrice);
unset($itemQty);
unset($temp);
}//end of if-statement
}//end of foreach
echo "<h1>Total Amount:<br></h1> ";
//print_r($totalAmountArray);
$sum;
foreach($totalAmountArray as $perItemPrice){
$sum += $perItemPrice;
}
echo "<b>SR. ".$sum."</b>";
echo "</div>";
?>
I am thinking of storing all the details returned from above foreach's into multidimensional array to have something like this:
[0] => itemName => itemQty => itemPrice <br>
[1] => itemName => itemQty => itemPrice <br>
[2] => itemName => itemQty => itemPrice <br>
[3] => itemName => itemQty => itemPrice <br>
.....
would this be the best way? and how can it be done? I am really unfamiliar with multidimensional arrays in practice (only in theory).
Thanks a lot for the help and advice,
I may be wrong but since you want an advise I just do not see the point on why would you use a two dimensional array in this situation (although I may misunderstood your question and may wrong but I think the best way to solve your problem is to create a class Item in that class has a variables itemName itemQty itemPrice and then store information about every object item in to an array
Hold an array of an array. Making multi dimensional arrays can get a little confusing. For each item, it holds an array of all its data. Another way is to make an object (class), say "items" which holds each piece of data from the form. Each form submission object is then put into an array for sorting and retrieval.
So it would be
[sudo PHP]
class foo
{
int formID
string submitterName
string bar
}
foo->formID = $row['id']
myArray[lastPosition + 1] = foo
for (int i = 0; i < foo.length; i++)
{
echo foo[i]->formID
}
I haven't touched PHP in years, sorry about the wierd half-PHP looking code, just thought I might deliver an answer quickly!

Displaying multidimensional array in php

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"

Categories