$query->result_array() wipes away list_fields() data - php

I'm having an issue where I call the result_array() function on n query object from in codeigniter:
$this->db->select(array('a','b','c'));
$query = $this->db->get('basic');
print_r($query->list_fields());
$test = $query->result_array();
print_r($query->list_fields());
When I run this code, or:
$query = $this->db->get('basic');
print_r($query->list_fields());
print_r($query->list_fields());
or:
$query = $this->db->get('basic');
$test = $query->result_array();
print_r($query->list_fields());
The second list_fields() function always returns an array size 0, the first returns the correct list of field names.
In the last example where there is only one list_fields() function, the array is again size zero.
Any guidance in this matter will be greatly appreciated. I need the list_fields() function to be accessible after I read the result_array().
Here is the result of the first block of code:
Array
(
[0] => site_id
[1] => institution
[2] => caller
[3] => call_complete
[4] => call_details
[5] => id
[6] => timestamp
)
Array
(
)
Thank you, for your help

That looks to be a bug in the database driver. For example, in CI_DB_mysqli_result:
public function list_fields()
{
$field_names = array();
while ($field = $this->result_id->fetch_field())
{
$field_names[] = $field->name;
}
return $field_names;
}
A subsequent call will return array() because the while loop seeks over all the fields and leaves the pointer at the end of the list.
However, in the result class, result_id is public, so you can use mysqli_result::field_seek:
$query = $this->db->get('basic');
var_dump($query->list_fields());
// this should be called before any call to list_fields()
$query->result_id->field_seek(0);
var_dump($query->list_fields());
However, this is bad practise, as this only works for mysqli; for mysql, you'll need this:
mysql_field_seek($query->result_id, 0);
and for mssql:
mssql_field_seek($query->result_id, 0);
The correct way to do this is really to fix it in the database drivers. See this pull request :-)

Related

Associative array from a database with codeigniter

On my models I try to write a php model that will get me a associative array from a database. But I don't quite know how to approach this.
So after I execute this SQL query:
SELECT balance_events.weight,balance_events.added_date,
balance_entries.mid FROM balance_events, balance_entries
WHERE balance_entries.added_date BETWEEN '2016-08-02' AND '2016-08-03'
AND balance_entries.ptid =12
AND balance_entries.beid = balance_events.id
I will get this table:
And from that table I want to extract a asociative array that it will look like this:
count = ['13'=>1, '6'=>4, '16'=>3, '4'=>3]
where 'mid'=>number of how many times that mid can be found in the table.
ex. mid '13'=>1 cause you can found it only once.
I think that I will have to use SQL COUNT function, but how I can aggregate all of this in a PHP model in codeigniter? I know how to configure controller and view, but I don't know how to actually do the actual php model that will get me the desired array.
Try this query may help you ,
$result = $this->db->select('balance_events.weight,balance_events.added_date,COUNT(balance_entries.mid) as mid_count')
->from('balance_events, balance_entries')
->where('balance_entries.added_date BETWEEN "2016-08-02" AND "2016-08-03" ')
->where('balance_entries.ptid','12')
->where('balance_entries.beid','balance_events.id')
->group_by('balance_entries.mid')
->get();
return $result->result_array();
I'm not sure how you would create this in SQL but since you tagged php, I wrote a function that would do just this.
<?php
$query = array(array("mid"=>13), array("mid"=>2), array("mid"=>13), array("mid" =>6), array("mid" => 13), array("mid" => 6));
function createMidArray($queryResult){
$returnArray = array();
foreach ($queryResult as $qr){
$returnArray[$qr['mid']]++;
}
return $returnArray;
}
print_r(createMidArray($query));
?>
The output of this was Array ( [13] => 3 [2] => 1 [6] => 2 ) which matches up to my inputted $query (which is a 2D array). I'm expecting the output of your query is stored in a similar array, but with more data and keys

php: Database Class with PDO. How can i make it better?

So I started to get a little more practice in php and want to create a object oriented forum. Therefor I want to have a Database class such like:
<?php
class Database {
public $databaseConnection;
function __construct(){
$this->databaseConnection = new PDO('sqlite:test.sq3', 0, 0);
$this->databaseConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$params = NULL;
$pdoStatement = $this->databaseConnection->prepare('CREATE TABLE IF NOT EXISTS user(
id INTEGER PRIMARY KEY,
username VARCHAR(40) NOT NULL UNIQUE,
numberoflogins INTEGER DEFAULT 0,
bannedstatus BOOLEAN DEFAULT FALSE,
dateofjoining TIME
)');
$pdoStatement->execute(array_values((array) $params));
}
function query($sql, $params = NULL){
$s = $this->databaseConnection->prepare($sql);
$s->execute(array_values((array) $params));
return $s;
}
function insert($table, $data){
self::query("INSERT INTO $table(" . join(',', array_keys($data)) . ')VALUES('. str_repeat('?,', count($data)-1). '?)', $data);
return $this->databaseConnection->lastInsertId();
}
}
Then I do this in the same script:
$database = new Database();
$database->insert('user',array( 'id' => 0,
'username' => 'gulaschsuppe',
'numberoflogins' => 23,
'bannedstatus' => TRUE,
'dateofjoining' => time()));
$searchID = 0;
$userData = $database->query('SELECT username FROM user WHERE id = 0');
$username = $userData->fetchAll();
print_r(array_values($username));
?>
I just wanted to see how things working. The most important part of the code is the class. I needed a little bit time to figure out how I get the information I wanted. This is what I get.
Array ( [0] => Array ( [username] => gulaschsuppe [0] => gulaschsuppe ) )
Everythings working, but I donĀ“t think this is best way to get the informations. I get an Array with an Array. Also, now there is no validation but first I want to focus on the functions query and insert.
So, can you explain how the last part with username => g. [0] => g. occured ?
I would like to know how I can improve the functions and please tell me when I do something totally wrong.
Array (
[0] => Array (
[username] => gulaschsuppe
[0] => gulaschsuppe
)
)
You're getting the result with both names columns (so you could do $row['username']) and numerically (so you can do $row[0]). This is the default PDO behavior. You need to use the PDO::FETCH_* constants in order to change the fetched results. PDO::FETCH_BOTH is the default value.
You can either set it when you're fetching:
$username = $userData->fetchAll(PDO::FETCH_ASSOC);
Or globally at some point:
$this->databaseConnection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
In the case that you want only a single column, you can use this fetch mode:
$usernames = $userData->fetchAll(PDO::FETCH_COLUMN);
// $usernames = array('gulaschsuppe');
This fetches only a single column for each row, without wrapping each result in another array (column 0 is fetched by default).
See the PDOStatement::fetch() documentation for more details.

Change global 2d array from a function PHP?

$q = $_POST['q'];
$inCart = isset($_COOKIE['cart']) ? unserialize($_COOKIE['cart']) : array();
function alreadyInCart() {
global $inCart, $good, $q;
foreach ($inCart as $inCart1) {
if ($inCart1[0] == $good->id) { // if this good already in cart
$inCart1[1] = $inCart1[1] + $q; // write sum of q's to existing array
return true; // and return true
}
}
return false; // return false if not
}
if (alreadyInCart() == false) { // if good added to cart for the first time
$inCart[] = array($good->id, $q); // add array at the end of array
}
Hello. So my problem is that I'm running a function to find out if $good->id is already inside of 2d $inCart array.
$inCart looks something like this:
Array
(
[0] => Array
(
[0] => 6
[1] => 1
)
[1] => Array
(
[0] => 5
[1] => 1
)
)
Where [0] is a good ID and [1] is an amount of this good in a cart.
So I tracked that function actually does what I want and returns true/false as expected, but looks like it only does it inside of itself. Cause if I put print_r($inCart1[1]) inside of a function it does add up and outputs the sum, as expected. But when I output the array at the end of the code (outside the function) the amount doesn't add up, just stays how it was before the function run.
Any ideas why that happens?
Ok, in case someone faces the same problem: found a solution.
Or should I say found a mistake?
The problem was with the foreach ($inCart as $inCart1). Must be replaced with foreach ($inCart as &$inCart1) in order to change array values in a loop. The other way, it just reads values, bit can't change them.

Codeigniter - passing multiple value to view

I am trying to build a month report with Codeigniter.
i have problem in parse value to view,
when i enable profiler, i get 12 month query
Controller
$this->load->model('dash_model');
$data1= $this->dash_model->get_user_all();
$ind = $this->dash_model->monthreport();
$this->output->enable_profiler(TRUE);
$data = array(
'mont' => $ind,
'blok' => $data1
);
print_r($data);
$this->parser->parse('blank', $data);
the output print_r data
Array
(
[mont] => Array
(
[0] => stdClass Object
(
[trans_email] => 0
)
)
and dash_model
for($i=1; $i<=12;)
{
$month=array("","01","2","3","4","5","6","7","8","9","10","11","12");
$m = $month[$i];
$query2=$this->db->query("select count(*) as trans_email from trans_email where lup LIKE '2014-$m%' ");
$i++;
}
return $query2->result();
how i get output select count(*) as trans_email from trans_email where lup LIKE '2014-01%' and next month to view ?
like
month 1 = 356 data
month 2 = 2000 data and next
i'm trying this : Codeigniter - passing multiple values to view
but nothing happens
update
i'm trying to add this code into dash_model
$i++;
$resultarray[$i]=$query2->result();
}
return $resultarray;
and i got some error
* Object of class stdClass could not be converted to string*
okay dude let me try to guest :D
let's assume you use array on your view, i can assume that because you initialize $data with array.
First make sure you read this userguide
on result_array() section.
then change $query->result(); to $query->result_array();
then try to var_dump() it, hope it's work
just pass it as
$data['mont'] = $ind;
$data['blok'] = $data1;
$this->parser->parse('blank', $data);
in the view get the data as of $ind as $mont
and $data1 as $blok.
You could do
$data = array();
$data['mont'] = $ind;
$data['blok'] = $data1;
Instead of declaring it then initializing it at the same time. (It also allow you to add/change data in it whenever you want in your controller).
Then do debug($data);to see if you got everything you want in $data.

How to call function inside controller inside foreach loop with different parameters value

i am trying to call m custom function repeatedly with same or different parameters value,inside foreach loop parameters depending upon value to key provided my foreach.
foreach ($result as $r) {
if($r->marks1==null || $r->marks2==null)
{
echo $r->p_code;
$toUpdate=$this->getResult($username,$r->p_code);
print_r($toUpdate);
}
}
but when i am printing the latest query result i am getting $toUpdate get appended by latest parameter query.
Array
(
[query] => select * from `result` where (`studentid` = ?) and `studentid` = ? and `ccode` = ? and `a_no` = ? order by `date` desc limit 1
[bindings] => Array
(
[0] => XYZ
[1] => XYZ
[2] => course123code
[3] => 12321
)
[time] => 0.18
)
my user name getting same, while course code is get overrides while finding second result.
i want to get the result getResult() inside foreach loop so that it may give the related result for different parameters value.
public function getLatestResult($username,$course_code)
{
$user=new User;
$currentDetailOfUser=$this->userCurrentDetail($username);
$userdetail=json_decode($currentDetailOfUser,true);
$username =$userdetail['username'];
$studentid =$userdetail['userid'];
$studentBatch =$userdetail['batch'];
$programCode =$userdetail['programCode'];
$activeSemester =$userdetail['activesemester'];
$condition_key=array(
'studentid' =>$studentid
);
$getCurrentResult1 =$user->getDetail('student_result',$condition_key);
$getCurrentResult2 =$user->getDetail('student_result',$condition_key);
$resultAssessment1=$getCurrentResult1->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',1)->orderBy('date','Desc')->limit(1)->get();
$resultAssessment2=$getCurrentResult2->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',2)->orderBy('date','Desc')->limit(1)->get();
$recentResult=array_merge($resultAssessment1,$resultAssessment2);
return $recentResult;
}
This is a bad practice if you are fetching data from db inside the foreach loop.
BTW you can do this by keeping all new result in same array by index its some unique value, it will be look like this-
$toUpdate=array();
foreach ($result as $r) {
if($r->marks1==null || $r->marks2==null)
{
echo $r->p_code;
$toUpdate[$r->p_code]=$this->getResult($username,$r->p_code); // added $r->p_code as index to Array - $toUpdate
}
}
print_r($toUpdate); // this will give all the related result according your parameters
[UPDATE]
Try using unset($yourarray) for your next request these array will be new and they assign the new value each time -
public function getLatestResult($username,$course_code)
{
$user=new User;
$currentDetailOfUser=$this->userCurrentDetail($username);
$userdetail=json_decode($currentDetailOfUser,true);
$username =$userdetail['username'];
$studentid =$userdetail['userid'];
$studentBatch =$userdetail['batch'];
$programCode =$userdetail['programCode'];
$activeSemester =$userdetail['activesemester'];
$condition_key=array(
'studentid' =>$studentid
);
$getCurrentResult1 =$user->getDetail('student_result',$condition_key);
$getCurrentResult2 =$user->getDetail('student_result',$condition_key);
$resultAssessment1=$getCurrentResult1->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',1)->orderBy('date','Desc')->limit(1)->get();
$resultAssessment2=$getCurrentResult2->where('studentid',$studentid)->where('course_code',$course_code)->where('assignment_no',2)->orderBy('date','Desc')->limit(1)->get();
unset($currentDetailOfUser);
unset($userdetail);
unset($condition_key);
unset($recentResult);
$recentResult=array_merge($resultAssessment1,$resultAssessment2);
return $recentResult;
}
Hope this can help you.

Categories