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;
}
Related
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
SELECT col FROM table
Say I have this query and I get the following result:
array(2) {
0 => array(1){
"COL"=>"value1"
},
1 => array(1){
"COL"=>"value2"
}
}
Is there some SQL statement I can use to get this from the same data:
array(2) {
0=>"value1",
1=>"value2"
}
I'm using zend framework and db2. If it can't be done through SQL, can it be done with Zend?
Thanks
EDIT: I should clarify, I can do this with a loop or a function. I was just wondering if there was a built-in way to do it to save a few lines of code and be all fancy smartpants.
you could try the fetchPairs() method. That might be what you're looking for, at least in a limited fashion.
The fetchPairs() method returns data in an array of key-value pairs,
as an associative array with a single entry per row. The key of this
associative array is taken from the first column returned by the
SELECT query. The value is taken from the second column returned by
the SELECT query. Any other columns returned by the query are
discarded.
You may also try and set the fetch method to Zend_Db::FETCH_COLUMN.
Zend_Db::FETCH_COLUMN: return data in an array of values. The value in
each array is the value returned by one column of the result set. By
default, this is the first column, indexed by 0.
$db->setFetchMode(Zend_Db::FETCH_COLUMN);
try a custom function like this:-
function myfuntion($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, myfuntion($value));
}
else {
$result[$key] = $value;
}
}
return $result;
}
Here is how I do it:
in my model:
public function getRecords() {
$select = $this->select();
return $this->fetchAll($select);
}
in my controller:
$records = $mdl->getRecords();
$recordsArray = $records->toArray();
I think the easiest way is :
public function my_function()
{
$db = Zend_Db_Table::getDefaultAdapter();
$results = $db->fetchAll("SELECT * FROM my_table");
/* if you want only one row, do something like this*/
/* $results = $db->fetchRow("SELECT * FROM my_table") */
return $results;
}
/* Then maybe in your controller you can call the function
and */
$results=my_function();
/*make values avelaible to the view*/
$this->view->$results=$results
Then inside the view : it depends on what your function resturns:
case: its fetchAll:
<?php foreach ($this->results as $item): ?>
<?=$item['address']?> /* access fields */
<?php endforeach ?>
case: its fetchRow: No need to use foreach().
I hope it helps.
I am building a function that acts like Drupal's variable_initialize() function that pulls all key/value pairs into a global variable. I am trying to find the proper parameters I need to put into fetchAll() to remove the row number and get basically what fetch(PDO::FETCH_ASSOC) does but for all returned rows.
I basically want fetchAll to return:
Array {
[name] = value,
[name2] = value2,
[name3] = value3,
}
The variable table is a simple 2 column table (name)|(value)
function variable_init() {
global $db, $variable;
$query = "SELECT * FROM variable";
$stmt = $db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(); //need help here
foreach($result as $name => $value) {
$variable[$name] = $value;
}
}
I have tried PDO_COLUMN/PDO_GROUP/etc... but I can't seem to offset the array to remove the row numbers. Thanks.
I think you may be getting confused about what PDOStatement::fetchAll() returns.
The method returns all rows (arrays or objects, depending on fetch style) in an array.
Try this
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$variable[$row['name']] = $row['value'];
}
Is it possible to transfer a fetch value to an array?
For example in my database table I have a column named vehicle, and inside that column, it contains:
vehicle1
vehicle2
vehicle3
All of that in one array.
Now is it possible to transfer it to an array? (array())?
Another question:
How can I echo it separately?
vehicle1
vehicle2
vehicle3
are all in one mysql array, how can I echo it one by one? Because if I echo the array the result would be the three vehicles. What I'm asking is that how can I echo the array that the result would be vehicle1 and if I echo it again, vehicle2. and so on.
$vehicles = array();
$sql = "SELECT `vehicle` FROM `table` WHERE 1";
$result = mysql_query($sql);
if ($result) {
while (($row = mysql_fetch_array($result)) !== false) {
$vehicles[] = $row['vehicle'];
// or
// $vehicles[] = $row; // store all columns in vehicle array
}
}
foreach($vehicles as $vehicle) {
echo "{$vehicle}<br />\n";
}
You can also create an array of arrays to store multiple details from the result of your queries.
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;