CodeIgniter passing array with queries into view - php

Hi I am having an issue getting the view to show any results for the following code.
Controller:
$datedue = 2011-01-27;
$username = $this->tank_auth->get_username();
$sql = "SELECT taskid FROM relationships WHERE username = ? AND datedue = ?";
$tasks = $this->db->query($sql, array($username, $datedue));
$count = 0;
$taskdetails = array();
foreach($tasks->result() as $row)
{
$taskid = $row->taskid;
$subsql = "SELECT * FROM tasks WHERE id = ?";
$taskdetails[$count] = $this->db->query($subsql, array($taskid));
$count++;
}
$data['taskdetails'] = $taskdetails;
$data['total'] = $count;
$this->header();
$this->load->view('dashboard', $data);
View:
<?php
foreach($taskdetails as $entry)
{
foreach($entry->result() as $row)
{
echo $row->name;
}
}
?>
Any help would be nice thanks.

The reason why your view is not displaying something is because you're query is not completely correct.
$datedue = 2011-01-27;
should be enclosed in quotes, since the date is a string.
$datedue = "2011-01-27";
Also, you're not correctly following the concept of MVC. All the database querying and results should occur inside of the Model. And all of the data handling inside the Controller.
The Controller nor the View should handle any of the database connections, that is the duty of the Model. Therefore I would advise to create a Model and put all of the Database querying in one or two functions. The Controller would then call these functions and receive the data back. Then it should manipulate it and pass it to the View in a clean matter (by this I mean, that the View should NEVER call result()
Here is how you're code should be structured:
CONTROLLER
class Tasks extends Controller {
function Tasks ()
{
parent::Controller();
$this->load->model('tasks_model');
$this->load->database();
}
function index()
{
$datedue = "2011-01-27";
$username = $this->tank_auth->get_username();
$tasks = $this->tasks_model->getTasks($username, $datedue);
$count = count($tasks);
$data['taskdetails'] = $tasks;
$data['total'] = $count;
$this->header();
$this->load->view('dashboard', $data);
}
}
MODEL
class Tasks_model extends Model {
function Tasks_model()
{
// Call the Model constructor
parent::Model();
}
function getTasks($username, $datedue) {
$sql = "SELECT taskid FROM relationships WHERE username = ? AND datedue = ?";
$tasks = $this->db->query($sql, array($username, $datedue));
$taskdetails = array();
foreach($tasks->result() as $row){
$taskid = $row->taskid;
array_push( $taskdetails, $this->getTasksDetails( $taskid ) );
}
return $taskdetails;
}
function getTasksDetails($taskid) {
$subsql = "SELECT * FROM tasks WHERE id = ?";
$taskdetails = $this->db->query($subsql, array($taskid));
return $taskdetails->row();
}
}
VIEW:
foreach($taskdetails as $task)
{
echo $task->name;
}

verify your task table contain the name field
view
foreach($taskdetails as $entry)
{
foreach($entry->result() as $row)
{
echo $row[0];
}
}
why you are passing array in this line
$taskdetails[$count] = $this->db->query($subsql, array($taskid));
instead write
$taskdetails[$count] = $this->db->query($subsql, $taskid);

Related

Cannot get query result from Model to Controller in Codeigniter

Trying to get result from database by calling stored procedure in code-igniter. Below is my controller & model. Model is working fine getting result from stored procedure and can show the result when I do print_r() in model. But I am not able to get the result of query in controller method. Not able to understand the error here.
Controller:
function weeklysalesstatus()
{
$this->data['rpt'] =$this->reports_model->weeklysalesstatus(true);
$this->data['page_title'] ='Weekly Sales Status [ Residential ]';
print_r("here...");
$this->page_construct('reports/weeklysalesstatus', $this->data);
}
Model:
public function weeklysalesstatus($sender = false)
{
$sql = 'select * from region';
$sql1 = 'CALL GetWeeklySalesStatus()';
$query = $this->db->query($sql1);
if(count($query) > 0) {
foreach (($query->result()) as $row) {
$data[] = $row;
//var_dump($data);
}
return $data;
} else {
print_r("no rows");
}
return $data;
}
The issue is somewhere in this line : $this->data[$rpt] = $this->reports_model->weeklysalesstatus();
But can't figure it out.
Thanks
EDIT:
These errors arise only when I call Stored Procedure CALL. For other queries it work perfectly. So is there any settings I need to do on Codeigniter DB class for calling a Stored procedure thru active record?
$q = $this->db->query('CALL GetWeeklySalesStatus');
Change this line to
$q = $this->db->query('CALL GetWeeklySalesStatus')->result();
In Model
public function weeklysalesstatus()
{
//$sql = 'select * from region';
$sql1 = 'CALL GetWeeklySalesStatus()';
$query = $this->db->query($sql1);
if(!empty($query))
{
$data = $query->result_array();
return $data;
}
else
{
return FALSE;
}
}
In Controller
function weeklysalesstatus()
{
$rpt =$this->reports_model->weeklysalesstatus();
if ($rpt == FALSE) {
echo "Empty";
} else {
$data['rpt'] = $rpt;
}
$data['page_title'] ='Weekly Sales Status [ Residential ]';
$this->page_construct('reports/weeklysalesstatus', $data);
}
Modify the controller like the following hope it works
function weeklysalesstatus()
{
$this->data['rpt'] =$this->reports_model->weeklysalesstatus();
$this->data['page_title'] ='Weekly Sales Status';
$this->page_construct('reports/weeklysalesstatus', $this->data);
}
your model
public function weeklysalesstatus($sender = false)
{
$sql = 'select * from region';
$sql1 = 'CALL GetWeeklySalesStatus()';
$query = $this->db->query($sql1);
$data["result"] = array();
if(count($query) > 0) {
foreach (($query->result()) as $row) {
$data["result"][] = $row;
//var_dump($data);
}
}
return $data;
}
your controller
function weeklysalesstatus()
{
$data['rpt'] =$this->reports_model->weeklysalesstatus(true);
$data['page_title'] ='Weekly Sales Status [ Residential ]';
print_r("here...");
$this->page_construct('reports/weeklysalesstatus', $data);
}

magento database sql not working

So do not have an idea why this function is not working? i am trying to select all the ids from the table but nothing is selected.
public function jobsArray()
{
$connection = Mage::getSingleton('core/resource')->getConnection('Envato_CustomConfig_Job');
$result = $connection->fetchAll("SELECT id FROM Envato_CustomConfig_Job");
$rows = array();
foreach($result as $record) {
$rows = ('value'=>$record, 'label'=>$record);
}
return $rows;
}
this function below works fine, I need the function above to do the same as teh function below.
public function toOptionArray()
{
return array(
array('value'=>1, 'label'=>'one'),
array('value'=>2, 'label'=>'Two'),
array('value'=>3, 'label'=>'Three'),
array('value'=>4, 'label'=>'Four')
);
}
There are a couple of issues with your code:
You're only selecting a single item (id, but later, I assume you're expecting an ID and a value).
$result = $connection->fetchAll("SELECT id FROM Envato_CustomConfig_Job");
record is an array from your SQL query, so you should be treating it as such. eg. $record['id']
$rows you want as an array, but you're overwriting it each time, so $rows[] = makes more sense
Something like:
public function jobsArray()
{
$connection = Mage::getSingleton('core/resource')->getConnection('Envato_CustomConfig_Job');
$result = $connection->fetchAll("SELECT id, label FROM Envato_CustomConfig_Job");
$rows = array();
foreach($result as $record) {
$rows[] = array('value'=>$record['id'], 'label'=>$record['label']);
}
return $rows;
}
Try using the core read/write resource. Change
$connection = Mage::getSingleton('core/resource')->getConnection('Envato_CustomConfig_Job');
To
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');

php class return array

I tried to get followers from MySQL usingy this class
class get_followers {
public $followers_arr = array();
public function __construct($user_id) {
$query = "select * from followsystem where following ='$user_id'";
$q = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($q);
if ($count > 0) {
while ($row = mysql_fetch_assoc($q)) {
array_push($this->followers_arr, $row['userid']);
}
}
return $this->followers_arr;
}
}
Then I initialize this class
$fol = new get_followers($userid);
$fol_arr = json_encode($fol);
echo $fol_arr;
Then I get
{"followers_arr":["1234","456"]}
but what i want want just to get this
["1234","456"]
How is that works?
I don't think you understand how constructors work. You can't return a value from a constructor because it's just used to instantiate the object. When you're doing $fol_arr = json_encode($fol); you're actually encoding the entire object, not it's return value.
If you really want to use a class to do this, you should add a method to the class and use that, like this:
class Followers {
public $followers_arr = array();
public $user_id = null;
public function __construct($user_id) {
$this->user_id = $user_id;
}
public function get()
{
$query = "select * from followsystem where following ='{$this->user_id}'";
$q = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($q);
if ($count > 0) {
while ($row = mysql_fetch_assoc($q)) {
array_push($this->followers_arr, $row['userid']);
}
}
return $this->followers_arr;
}
}
And use it like this:
$fol = new Followers($userid);
$fol_arr = json_encode($fol->get());
echo $fol_arr;
The solution to your problem is to do $fol_arr = json_encode($fol->followers_arr);
Nonetheless, making a class in this case is completely obsolete, since you only make it as a wrapper for a single function you want to execute (called get_followers) Instead of making a class, you could simply make the following:
function get_followers($user_id) {
$followers_arr = [];
$query = "select * from followsystem where following ='$user_id'";
$q = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($q);
if ($count > 0) {
while ($row = mysql_fetch_assoc($q)) {
array_push($followers_arr, $row['userid']);
}
}
return $followers_arr;
}
$fol = get_followers($userid);
$fol_arr = json_encode($fol);
echo $fol_arr;
There is no need to put it in a class unless the class serves the purpose of combining a few functions and variables to create a behaviour.

Re create as objects and classes PHP

I'm a little bit stumped. I've never messed around with objects and classes too much in PHP, but someone recommended that I re-did some code with it.
What I'm trying to do is make $auctions an object property, while saving all of the row data to it.
Right now, I do echo $auctions[1]['title']; to echo out the listing where id=1 title.
And I wish to re-create it so that it would be an object.
Here's my current code,
$sqlquery = "SELECT * FROM auctions";
if ($result = $db->query($sqlquery)) {
while ($row = $result->fetch_assoc()) {
$auctions[$row['id']]['id'] = $row['id'];
$auctions[$row['id']]['title'] = $row['title'];
$auctions[$row['id']]['featured_image'] = $row['featured_image'];
$auctions[$row['id']]['description'] = $row['description'];
$auctions[$row['id']]['date'] = $row['date'];
$auctions[$row['id']]['location'] = $row['location'];
$auctions[$row['id']]['highlights'] = $row['highlights'];
$auctions[$row['id']]['catagories'] = $row['catagories'];
$auctions[$row['id']]['notes'] = $row['notes'];
$auctions[$row['id']]['terms'] = $row['terms'];
$auctions[$row['id']]['contact'] = $row['contact'];
}
}
I don't have any idea on how to accomplish this, but if someone could give me a little hint to point me in the direction, it would be very appreciated! :)
Create a class auctions with all the needed member variables that you listed above (e.g. id, title, feature_image etc.). Next create a setter method (e.g. setValues()) inside the class that can accept the $row.
$sqlquery = "SELECT * FROM auctions";
$auction = new Auctions();
if ($result = $db->query($sqlquery)) {
while ($row = $result->fetch_assoc()) {
$auction->setValues( $row );
// do something with $auction...
}
}
Instead of a explicit setter method, You may also use magic method __set().
I'll write a minimal snippet here now:
First let create a base class for all our models:
abstract class Model() {
public $fields = array();
private $data = array();
public function setValues(array $vals) {
foreach($vals as $key=>$value) {
if (in_array($key, static::$fields)) {
$this->data[$key] = $value;
}
}
}
public function get($key) {
if (in_array($key, static::$fields) && isset($this->data[$key])) {
return $this->data[$key];
}
return null; // or throw Exception)
}
}
Next, create some concrete model:
class Users extends Model {
public static $fields = array('id', 'name');
}
And we can use it now:
$users = array();
$sqlquery = "SELECT * FROM Users";
if ($result = $db->query($sqlquery)) {
while ($row = $result->fetch_assoc()) {
$user = new User();
$user->setValues($row);
$users[] = $user;
}
}
You can to add some user-specific methods (aka login) to User model directly..
Also you should to implement other Model methods, like getById, getByQuery, save and other, and no use direct sql queries, because models can do this itself
You can store the values in a object like
$obj = new stdClass; //create new standard class object
$obj->id = $row['id']; //assign property value
$obj->title = $row['title'];
//further properties
... and so on
You really are trying to create an array of objects (instances of a type containing info for one auction. Something like this:
class Auction
{
var $id = null;
var $title = null;
var $featured_image = null;
var $description = null;
var $date = null;
var $location = null;
var $highlights = null;
var $catagories = null;
var $notes = null;
var $terms = null;
var $contact = null;
}
$sqlquery = "SELECT * FROM auctions";
if ($result = $db->query($sqlquery)) {
while ($row = $result->fetch_assoc()) {
$newAuction = new Auction();
$newAuction->id = $row['id'];
$newAuction->title = $row['title'];
$newAuction->featured_image = $row['featured_image'];
$newAuction->description = $row['description'];
$newAuction->date = $row['date'];
$newAuction->location = $row['location'];
$newAuction->highlights = $row['highlights'];
$newAuction->catagories = $row['catagories'];
$newAuction->notes = $row['notes'];
$newAuction->terms = $row['terms'];
$newAuction->contact = $row['contact'];
$auctions[$row['id']] = $newAuction;
}
}
Please note that you have misspelled "categories" (you have "catagories").
I advice you to use PDO
class Auction
{
public $id;
public $title;
public $featured_image;
public $description;
public $date;
public $location;
public $highlights;
public $catagories;
public $notes;
public $terms;
public $contact;
// This will return $all being an array of objects of class Auction
public static function getAll() {
$query = "SELECT * FROM auctions";
$statement = $db->prepare($query);
if (!$statement->execute())
return false;
$all = $statement->fetchAll(PDO::FETCH_CLASS, "Auction");
return $all;
}
}

select-from-where query not working in codeigniter model

I am trying to select the details of the users from a table in mysql database but it is not working. This is the code in my model :-
public function getuserdetails()
{
$user_email = $this->input->post('email');
$query_userdetails = $this->db->query("SELECT *
FROM users WHERE email = '$user_email' ");
return $query_userdetails->result_array();
}
This is not working. But if I put the actual email id in the query instead of $user_email it works but not properly i.e if I use :-
$query_userdetails = $this->db->query("SELECT * FROM users WHERE
email = 'myemail#gmail.com' ");
In this case it returns a result. My controller code to accept the result is :-
$data['details'] = $this->model_userdetails->getuserdetails();
But the problem is that when I access $details in view :-
echo $details['name']."<br />";
it does not recognize 'name'. name is the field in the database where the name of the users are stored. But if I try to retrieve it in a foreach loop it is working :-
foreach($details as $udetails)
{
echo $udetails['name']."<br />";
}
Run queries as per codeigniter suggestion
$query_userdetails = $this->db->query("SELECT * FROM users WHERE email = ?", array($user_email));
http://ellislab.com/codeigniter/user-guide/database/queries.html search for Query Bindings
I would try:
$query_userdetails = $this->db->query("SELECT * FROM users WHERE email = '". $user_email ."'");
I have solved the part where only foreach loop would work.
If we use row_array instead of returning result_array() the foreach constraint to diplay goes away.
Now I want to select the name from the database where email is $user_email
You have to write like this
public function getuserdetails()
{
$user_email = $this->input->post('email');
$this->db->where('email', $user_email)
->get('users')
->result_array();
}
After this, in view, you must to write like this
foreach($details as $udetails)
{
echo $udetails['name']."<br />";
}
You can try like This:
[CONTROLLER]
$data = array();
$data['udetails'] = $this->UserModel->getuserdetails();
$this->load->view('welcome_message',$data);
[MODEL]
public function getuserdetails() {
$user_email = 'webmaster';
$userdetails = $this->db->query("SELECT * FROM users WHERE umail = '$user_email' ");
return $userdetails->result();
}
[VIEW]
<?php
foreach($udetails as $row)
{
echo($row->uname.'<br/>');
echo($row->uname);
}
?>
Try this please it will help you.
Model
public function getuserdetails()
{
$user_email = $this->input->post('email');
$this->db->select("*");
$this->db->from('users');
$this->db->where('email',$user_email);
$query = $this->db->get();
$result= $query->result();
}
Controller
$data['details'] = $this->model_userdetails->getuserdetails();
view
foreach($details as $detail)
{
echo $detail->name;
echo $detail->email;
}

Categories