One dimensional array results from SQL column - php

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.

Related

PHP function foreach/while loop save multiple or array of values

I have this code which I want to save all of the column values taken from Mysql database.
<?php
$db = mysqli_connect('localhost','mysqluser','password','test');
function itemName($db){
$data=$db->query("select * from item");
foreach($data as $k=>$v){
return $v['item_name'];
}
}
echo itemName($db); //output:item1
?>
The problem is above code only returned the first row of data. Although I can use echo inside of the foreach loop like "echo $v['item_name'];", then call the function which will output all the values like item1 item2 item2 etc. My question is how can I use return to save all off the values equivalent like echo does, but not immediately echoed out.
Collect data in array and return this array from your function:
$db = mysqli_connect('localhost','mysqluser','password','test');
function itemName($db){
$data=$db->query("select * from item");
$result = [];
foreach($data as $v){
$result[] = $v['item_name'];
}
return $result;
}
print_r(itemName($db));

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.

PHP/MySQL: How to get multiple values from a PHP database method

Sorry for the incredibly newbie question, but I can see myself drifting into bad practices if I don't ask.
I have a PHP method that I want to return all the values of a given database column, in order to place the contents in a dropdown menu for a HTML form. I could obviously construct the whole HTML in the PHP method and return that as a string, but I imagine this is pretty bad practice.
Since PHP methods can only return one value, I imagine I'll need to call the method several times to populate the dropdown menu, or pass an array from the method.
What would be a good solution to this (presumably) common problem? Thanks.
Well, an array is one value, containing tons of other values. So just have your method return a array of results.
edit: as Hammerstein points out you could use objects but its as good/bad as arrays depending on context. Very similar.
You could use an object as your return type. So;
class MyReturnValue
{
public $Value1;
public $Value2;
}
function getMyValues()
{
$results = GetDatabaseValues( ); // Assume this returns an associative array
$result = new MyReturnValue();
$result.Value1 = $results["Value1"];
$result.Value2 = $results["Value2"];
}
Then in your code, you can refer to $result.Value1 etc.
There is no PHP function to do this, so you will have to form an array from the results.
$column = array()
$query = mysql_query("SELECT * FROM table ORDER BY id ASC");
while($row = mysql_fetch_array($query)){
$column[] = $row[$key]
}
Then pass $column to your view(HTML)
foreach($column as $value)
{
echo "<li>" . $value . "</li>";
}
You can have arrays in arrays, so if you have a table with several columns you could assign them to an array as separate arrays:
$all_results = array();
foreach($rowInDatabase as $key => $value){
// each row will be an array with a key of column name and value of column content depending how you get the data from the DB.
$colname = $key;
$colVal = $value; //this is an array
$all_results[$colname] = $colVal; //append the current row to the array
}
}
code like this will populate your array with an array per row of the table so if there are ten rows and five columns you could get row 2 column 3 with $all_results[1][2]; (as they start from 0).
Not quite sure I understand what you want to do fully, but you could always pass the result back from the method, and then loop through it in your HTML.
Your method would be something like:
public function my_method()
{
$result = $db->query($sql_here);
return $result;
}
And then your HTML would be
<select>
<?
$result = $class->my_method();
while($row = $result->fetch_assoc())
{
echo '<option>'.$row['some_col'].'</option>';
}
?>
</select>

how to handle associative array in php

I have written a code in php that deals with php and mysql associative array.
I have wirtten a query in SQL as
$sql=mysql_query("select x,y from table_name");
Extracted value in associative array as
while($row=mysql_fetch_assoc($sql))
{
foreach ($row as $value1=>$value) {
...........
//$a[value1]=convert($row{'y'}); //this is wrong as i am always getting {"x":"value return from function after passing $row{'y'}","y":"value return from function after passing $row{'y'}".....ans so on} i.e same value in both the key.
}
}
What my problem is I want to use some function on one of the value from associative array as convert($row{'y'}) shown above and after the value is return from the function again i want that in associative array as
{"x":"value1","y":"value return from function after passing $row{'y'}".....ans so on} again.
How do I achieve this?
Thanks in advance.
while($row=mysql_fetch_assoc($sql))
{
$row['y'] = convert($row['y']);
}
$result = array();
while($row = mysql_fetch_assoc($sql)) {
if($row == 'someCondition') {
$result = someFunction($row[]);
} else {
$result = $row[];
}
}
now $result will hold all the returned value as an associative array. you can go ahead and use nested if. if you want to add some more condition.
If I am interpreting your question right you want something like this:
while($row = mysql_fetch_assoc($sql) {
$a[] = array(
'x' => $row['x'],
'y' => convert($row['y'])
);
}
Or, if you need the data to look up the y value based on x:
$a[$row['x']] = convert($row['y']);

Codeigniter/PHP: Format db query as an array

$this->db->select('id, user_id')->from('be_users')->where('id',$user_id);
$data['user_individual'] = $this->db->get();
If this is my db query, how do I get an array of one db row...
ie. I want to do something like $data['user_individual']['id']->format_as_array...
CodeIgniter provides several methods to perform on query results.
See here: https://codeigniter.com/user_guide/database/results.html
result() returns an array of PHP objects.
row() returns a single PHP object for that row.
result_array() returns an array of arrays.
row_array() returns a single array for that row.
row() and row_array() optionally take a parameter which is the number of the row you'd like to return.
Beyond this, it's difficult to tell exactly what you're asking for. You should be able to get your data out exactly as you like with these methods.
Edit:
Incidentally, the way to access these methods is through the query object returned from the $this->db->get() call:
$query = $this->db->get();
$rows = $query->result(); //array of objects
$rows_array = $query->result_array(); //array of arrays
$row = $query->row(); //single object
$row_array = $query->row_array(); //single array
When you use $this->db->get(); you can use $this->db->result(); which returns an arrayobject.
$query = $this->db->get('table_name');
foreach ($query->result() as $row)
{
echo $row->title;
}
See: http://codeigniter.com/user_guide/database/results.html for details on how to obtain resultsets from the database.
Instead of $ this-> db-> get () use $ this-> db-> row_array ();
$this->db->select('id, user_id')->from('be_users')->where('id',$user_id);
$data['user_individual'] = $this->db->row_array();
/**
* format_database_array
*
* Lets you format the database object data to array
#access public
#param String $db_object : database query object
#return String : Return array with data
*/
if ( ! function_exists('format_database_array'))
{
function format_database_array($db_object)
{
$db_array = array();
if($db_object-> num_rows >0)
{
foreach ($db_object->result_array() as $row)
{
foreach ($row as $key => $value)
{
$db_array[$key] = $value;
}
}
}
return $db_array;
}
}

Categories