I have following model function:
function getdata_naoh($datetest2) {
$result = $this->db1->query("select round(avg(cast(t_dtl.hasil_m as decimal(6,4))),4) as hasil_m from t_hdr JOIN t_dtl ON t_hdr.headerid = t_dtl.headerid where id_solvent ='NaOH' AND status='ok' AND concentrate='0.0100' AND date_start <='$datetest2' AND date_finish >='$datetest2'");
if($result->num_rows()>0) {
return $result->result_array();
}else {
return array();
}
}
And a controller function:
function get_NaOH() {
$date_analysis = trim($this->input->post('date_analysis'));
$datetest = trim($this->input->post('date_analysis'));
$datetest2 = substr($datetest,6,4).'-'.substr($datetest,3,2).'-'.substr($datetest,0,2);
$dtnaoh = $this->M_tambahan->getdata_naoh($datetest2);
$data1 = 0;
foreach($dtnaoh as $row) {
$data1 = $row['hasil_m'];
}
$data = $data1;
echo $data;
}
The query result would be like:
| hasil_m |
| ----------- |
| 0.0100 |
I want to get hasil_m column, according to the controller function, i set variable data1 = 0
then in foreach statement change the value as a result from hasil_m but when i echo variable $data i still getting data1 value = 0, did i miss something ?
Any help would be appreciated greatly, thank you.
In your loop, you're overwriting the variable with the new value. If you want to sum all of the hasil_m data into $data1 then simply modify your foreach loop as the following:
foreach($dtnaoh as $row) {
$data1 += $row['hasil_m'];
}
For debugging purposes, could you update your question to show exactly what the query returns?
Edit
Seems you've got float's! You'll need to harness floatval() in your loop to pass the values through:
foreach($dtnaoh as $row) {
$data1 += floatval($row['hasil_m']);
}
This happens because your initial variable ($data1) is treated as a string. Meaning it doesn't and won't show the float values, treating it as a whole number.
Related
I'm trying to get results from a database and return the data to my page.
I have 2 files, findtask, and functions.
In functions I have some code that grabs all my data from the table.
I then used a while loop to grab the stuff if I echo the results from the functions script it returns as it should id 1 2 and 3, my issue starts when trying to get the result from findtask script that only gets last result.
<?php
public function ShowOpenTasks ()
{
//i leave usersemail blank, because i only want tasks to show on this page if there not assigned.
$query = "SELECT * FROM `tasks` WHERE `usersemail` = ''";
if(!$result = mysqli_query($this->db, $query)) {
exit(mysqli_error($this->db));
}
$data = [];
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$data = $row;
echo $data['id'];
}
}
return $data;
}
?>
My findtask page is
require __DIR__ . '/lib/functions.php';
$app = new FunctionClass();
$task = $app->ShowOpenTasks();
echo $task['id'] //id being the name of the id table of the task.
This one will only turn the last id for some reason.
What is wrong and how can this be fixed?
It will only return last id since you are setting data to equal row
$data = $row;
So each row you replace it with the last one.
I guess you want an array instead, so you could do:
$data[] = $row;
then to print out all tasks:
$task = $app->ShowOpenTasks();
print_r($task);
This would give you an array of results.
I'm trying to combine two tables from a database, and based on my first one, I want to retrieve some value from the other one, and add them to an array.
Here's my problem:
My first database looks like that:
FIRST TABLE:
id, credit_type, association_name, address, city, province, postal_code, country, cycle_type, cycle_begin, cycle_months
My second database instead looks like that:
SECOND TABLE:
id, association_id, designation_name
The id in my first table matches the association_id in my second table so I don't need an INNER JOIN.
My approach is the following:
<?php
public function my_function()
{
$sql = ee()->db->select('*')->from('first_table')->get();
$data['database'] = [];
if ($sql->num_rows() > 0)
{
foreach($sql->result_array() as $row)
{
$id[] = $row['id'];
$data['database'][] = $row;
}
}
foreach ($data['database'] as $key => $value) {
$association_query = ee()->db->query("SELECT * FROM second_table WHERE id = $id");
foreach($association_query->result_array() as $row_two)
{
if ($association_query->num_rows() > 0)
{
$data['database'][$key]['associations'][] = $row_two['designation_name'];
}
}
}
return ee()->load->view('index', $data, true);
}
?>
The sintax ee()->db->select('*') is a prepared statment from expression engine and it's equal to SELECT * FROM first_table (sanitaized).
So as you can see, I try to pass the value $id, which is an array, to my query. The thing is that as soon as I push the value like that $id[] = $row['id'] I create a nice array, but when I loop through my foreach loop, it multiplies my array in many other arrays so I'm not able to run my query, even if I'm technically in a foreach loop.
Plus, as soon as I try to push the result of my query in my array, let's say changing the id in a static id for instance id=3, I obtain a really weird result, like so many arrays repeated with 1 value, 2 value, 3 value and so on, when I'd like to push my key 'association' only where it is presented in the other table.
If you won't do it on SQL, at least don't execute the second query so many times.
<?php
public function my_function()
{
$assocs = array();
$data = array('database' => array());
$association_query = ee()->db->query("SELECT * FROM second_table");
if ($association_query->num_rows() > 0) {
foreach($association_query->result_array() as $row) {
$assocs[$row['association_id'][] = $row['designation_name'];
}
}
$sql = ee()->db->select('*')->from('first_table')->get();
if ($sql->num_rows() > 0) {
foreach($sql->result_array() as $row) {
$id_check = $row['id'];
if (isset($assocs[$id_check])) {
$row ['associations'] = $assocs[$id_check] ;
}
$data['database'][] = $row;
}
}
return ee()->load->view('index', $data, true);
}
?>
Regards
I'm trying to show list of countries by the use of PHP function.
Here's the database value that I'm retrieving on. (cropped)
Here's the function that I'm retrieving the data.
Code:
public function get_countries() {
$list_country = array();
$query = $this->db->prepare("SELECT name FROM country");
$query->execute();
while($r = $query->fetch(PDO::FETCH_ASSOC)) {
$list_country[] = $r['name'];
}
return $list_country;
}
Then here's the code where I echo all the data.
<?php
while (list($country) = $general->get_countries()) {
echo $country;
}
?>
Unfortunately, it just all echo the same value over and over again.
Any solution for this? Like echo-ing all the data instead of the same data over and over again?
<?php
$country_array = $general->get_countries();
foreach ($country_array as $country) {
echo $country;
}
?>
You don't need the while() as you already fetched all countries with get_countries() function. Moreover, with list() you retrieve only the n array elements where n is the number of variables inside list() function.
So, why are you getting every time the same value?
Because you're calling every time a db function for read country content and every time you're retrieving the same value (the first)
$query = $PDO->prepare("SELECT blah FROM table");
$country = array();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$country[] = $row['blah'];
}
That code worked for me. You can set some exception if the query returns null this would suppress your warnings in the while loop.
Hope that helps
I have a Mysql query that gives the following result as using
while($row = mysql_fetch_array($res))
x | 12432
y | 232432
z | 323423
I want to take each column and put it in a new array in order to export them in a table that would look like
x | y | z
12432 | 232432 | 323423
If I fetch the same query more than once, the second row does not show up.
Can you please help?
Edit: Switch to mysqli (or PDO) as soon as you can! Plenty of reasons can be found in searchengines, so im gonna leave that to you.
You can use a nested loop to do this:
$array = array();
while($row = mysql_fetch_array($res)){
foreach($res as $key=>$value){
$array[$key][] = $value;
}
}
The first round of the while will give the $array the key-names and their first value, the next litterations through the loop will only add values
That is the code that worked for me.
while($row = mysql_fetch_array($res)){
$clients[] = $row[0];
$stats[] = $row[1];
}
foreach ($clients as $client)
{
echo "<td>$client</td>";
}
echo "</tr><tr>";
foreach ($stats as $stat)
{
echo "<td>$stat</td>";
}
I have to make a breadcrumb menu which comes database.
So made this function
function file_list($path) {
$result = array();
$q = "SELECT staticTitle,staticId,parentId FROM tbl_static_pages WHERE staticId = $path";
$run = mysql_query($q);
while($row = mysql_fetch_array($run)) {
if($row['parentId'] > 1) {
echo $row['staticTitle'];
$result = file_list($row['parentId']);
return $result; // INSERTED
}else {
return $result;
}
}
I have a database structure like this:
id | parentId | title
3 | 1 | keyword
28 | 3 | xxx
31 | 28 | business
I want to output like this business -> xxx -> keyword
I want to run this function until $row['parentId'] = 1.When I echo the title, I got correct result.When I try it to store it in array, I always get single value.
How can I return an array in recursive array?
I REALLY don't like the idea of recursive calls on the database. If this is a "breadcrumbs" database table, how big could it possibly be? ...I mean size is probably not a concern.
I would like to suggest that you pull the full table out (3 columns, all rows) and assign the resultset to a php variable. This means you only ever make one trip to the database -- and that's a good thing.
Code: (Demo)
function breadcrumber($array,$id){
static $result=[]; // declare the storage variable without losing elements during recursion
if(isset($array[$id])){ // if target exists
$result[]=$array[$id]['title']; // store title text
$parent=$array[$id]['parentId']; // assign new target
unset($array[$id]); // remove possibility of an infinite loop
breadcrumber($array,$parent); // recurse
}
return $result;
}
$resultset=[
['id'=>3,'parentId'=>1,'title'=>'keyword'],
['id'=>28,'parentId'=>3,'title'=>'xxx'],
['id'=>31,'parentId'=>28,'title'=>'business']
];
echo implode(' -> ',breadcrumber(array_column($resultset,NULL,'id'),31));
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-assign associative keys for easy lookup
Output:
business -> xxx -> keyword
...and here is another demo using your second set of data
Try this:
function file_list($path)
{
$result = array();
$q = "SELECT staticTitle,staticId,parentId FROM tbl_static_pages WHERE staticId = $path";
$run = mysql_query($q);
$results = array();
while ($row = mysql_fetch_array($run))
{
if ($row['parentId'] > 1)
{
echo $row['staticTitle'];
$results = array_merge($results, file_list($row['parentId']));
}
else
{
$results[] = $result;
}
}
return $results;
}
Few things that are not clear from your question:
Breadcrumbs are usually not recursive, so I suppose you do NOT want to actually return a recursive array (array where every element is again array). If you want, follow comment by #midhunjose
Do you expect the query to ever return multiple records?
Swap the order of array_merge arguments, if you want the parent before child in resulting array.
Try this:
$result[] = file_list($row['parentId']);
instand of
$result = file_list($row['parentId']);