return variables from array using a function - php

I retrieve data from database using this query:
SELECT * FROM tickets_departement_groups WHERE group_id = '{$user_group}'
$user_group is already defined, and I fetch the data using mysql_fetch_array, like this:
foreach ($query->result_array() as $row)
{
return $row['departement_id'];
}
All this is under a function called get_departement_id(), So when I do echo get_departement_id();
it prints last departement ID, but I have many of them. What I want to do is to output all the department IDs for a given query.

create and array and return the array?
$id_list = array();
foreach($query->result_array() as $row){
$id_list[] = $row['departement_id'];
}
return $id_list;

Related

Pushing values and keys to an multidimensional array from the database inside a foreach loop without repetitions

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

Get All Indexes Of array in codeigniter

Here Is MY Output OF problem i want to get all reciver_id indexes from this array and after getting all indexes i want to get the result from another table users against these id's
$data['cat_row'] = $this->messages_model->get_sentnotify($user_id);
foreach($data['cat_row'] as $key){
$profile = $key['reciver_id'];
}
$data['profile'] = $this->messages_model->Sender_profile($profile);
through this code i get only 1 value of first index how to get all...
getting all i want to get users from other table against each id
function Sender_profile($profile)
{
$this->db->where('id', $profile);
$query = $this->db->get($this->db_table2);
return $query->result_array();
}
kindly help me about sql also how i get all values from database in one iteration
Code Part 1
Get all reciver_id in an array like follows:
$data['cat_row'] = $this->messages_model->get_sentnotify($user_id);
$profile = [];
foreach($data['cat_row'] as $key){
array_push($profile, $key['reciver_id']);
}
$data['profile'] = $this->messages_model->Sender_profile($profile);
Code Part 2
Use Codeigniter's where_in() function.
function Sender_profile($profile) {
$this->db->where_in('id', $profile);
$query = $this->db->get($this->db_table2);
return $query->result_array();
}
In your controller , you need to access all your receiver_id then modify your foreach loop:
$i=0;
foreach($data['cat_row'] as $key){
$profile[$i] = $key['reciver_id'];
$i++;
}
Now you have all your receiver_id in $profile array. and pass this array in controller function and should query like this:
SELECT * FROM table WHERE id IN (5,4,3,1,6);// Just for example you need to modify your query according to your need.

Loop through fetchall without knowing the fields php

I have a simple query which will fetch all from a users tables
$query = $this->pdo->prepare('SELECT * FROM `users`');
$query->execute();
return $query->fetchAll();
Then i would have a foreach loop like
$results = $User->getUser();
foreach($results as $result){
echo $result['fname'];
echo $result['lname'];
}
But is there a way to display each of the fields without writing each field name?
First, fix your return fetchAll to specify the return style like so:
return $query->fetchAll(PDO::FETCH_ASSOC);
Then you can use an inner loop with your outter loop like so:
//get the results
$results = $User->getUser();
//loop over the results, setting $result to an array representing each row
foreach($results as $result){
//loop over each $result (row), setting $key to the column name and $value to the value in the column.
foreach($result as $key=>$value){
//echo the key and value.
echo "{$key} = {$value}<br>";
}
}
This will output all columns and their value regardless of what columns there are in the array. Following the comments, you can see what I do is, using your code, loop over the outer array that is an array of each row from the query. Then loop over the array from each row getting the column name and the value in that column. For now I am just echo'ing out the column and value. You would likely want to do more like echo this out to a table or whatever your end goal is.

display multiple rows from mysql in a php function

I have this PHP function i am using to retrieve rows from a mysql database:
$stmt = $pdo_conn->prepare("SELECT * from admin where sequence > :sequence ");
$stmt->execute(array(':sequence' => $user_sequence));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
$results=array();
foreach($records as $results) {
return $results;
}
here i am calling the function:
$test = AdminUserSessionID2('2');
echo $test["forename"];
but it is only displaying one row, what have i done wrong which is making it not display all rows?
Why return in foreach? Of course it will return just the first row. It's like saying foreach(rows as row){ return row; }.
<?php
function MyFunction($user_sequence){
global $pdo_conn;
$stmt = $pdo_conn->prepare("SELECT * from admin where sequence > :sequence;");
$stmt->execute(array(':sequence' => $user_sequence));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $records;
}
var_dump(MyFunction($user_sequence));
?>
You are assigning results as an empty array.
Then assigning it as the first item of records and returning it.
Try:
foreach($records as $row) {
array_push($results, $row)
}
You can't return multiple data/results in a foreach loop, because the first return will end the function. It's better to return the full array/records and do a foreach loop outside the function.
The $results array is getting returned, which should then be looped outside of the function
Try this:
function AdminUserSessionID2($user_sequence){
$stmt = $pdo_conn->prepare('SELECT * from admin where sequence > :sequence');
$stmt->execute(array(':sequence' => $user_sequence));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $records;
}
No-one has pointed out that return will exit your current function directly preventing any further processing, and this is why you get just one row output. Your specific code based on what you want to achieve would be:
$stmt = $pdo_conn->prepare("SELECT * from admin where sequence > :sequence ");
$stmt->execute(array(':sequence' => $user_sequence));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
$results=array();
foreach($records as $results) {
$test = AdminUserSessionID2('2');
echo $test["forename"];
}
See: http://php.net/return

Creating multidimensional array from existing arrays with variable variables

I'm creating a class function which accepts a mysql query result and returns a multidimensional array where the first array pointer is the table column and the second pointer is a numeric indicator of its position in the MySQL data.
Eg the table has the following columns:
Groupname
Groupid
Groupurl
And the way I want to call this is:
$arrayname[groupname][1];
I have formed 2 arrays already which are:
$colnames which contains all columns from the specific mysql query and
$$colname which is a variable variable of the column name containing all the data in each column. Eg: $groupurl is an array with all the data from that column.
I can't seem to get a loop to join the arrays as a multidimensional object and while I can manually do this for a specific table, it's a class function, and the variable variable part is breaking me =\
================ Thanks to IMSoP who gave me the idea, the solution is ==================
$result in the function is a successful MySQL Query on a table.
function tableAsMatrix($result)
{
//declare $results as array for use in loop
$results = array();
//this gets all the col names and sets them as $colnames[]
while( $cols = $result->fetch_field() )
{
$colnames[] = $cols->name;
}
//this loops through and assigns all cols as multidimensional $results[colname][id]
foreach ($colnames as $fields)
{
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
foreach($colnames as $field)
{
$results[$field][] = $row[$field];
}
}
}
//return to object
return $results;
}
The function I used is:
function tableAsMatrix($result)
{
//declare $results as array for use in loop
$results = array();
//this gets all the col names and sets them as $colnames[]
while( $cols = $result->fetch_field() )
{
$colnames[] = $cols->name;
}
//this loops through and assigns all cols as multidimensional $results[colname][id]
foreach ($colnames as $fields)
{
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
foreach($colnames as $field)
{
$results[$field][] = $row[$field];
}
}
}
//return to object
return $results;
}

Categories