I want to load all my rows of column "name" in my table "districts".
I can already read the first row but not more then that.
My Controller:
public function showdataAction()
{
$districtMapper = new Backoffice_Model_DistrictMapper();
$array = $districtMapper->read();
Zend_Debug::dump($array);
}
My DistrictMapper:
public function read()
{
$table = $this->_dbTable;
$columns = array('wijk' => 'wijk', 'coords' => 'coords', );
$select = $table->select() ->from($table, $columns) ->order('wijk ASC');
if ($row = $table->fetchRow($select)) {
return $row->toArray();
}
throw new Exception('The requested data cannot be found');
}
In my Controller I have Zend_Debug::dump($array) and the result is:
array(2) {
["wijk"] => string(10) "Binnenstad"
["coords"] => string(2186) "3.72448685517794,51.0601522198842,
0 3.72577413282654,51.0597215800093,0 3.72594328459339,
51.0600395135711,0 3.72699385985136, 51.060876600363,
0 3.72764765694006,51.0608474287073,
0 3.7281167878913,51.0605006616679,0 3.72955689560896,
51.059999738927"
}
Only the first row ... How can I can convert the read function so I can load all the rows?
public function read()
{
$table = $this->_dbTable;
$columns = array('wijk' => 'wijk', 'coords' => 'coords', );
$select = $table->select() ->from($table, $columns) ->order('wijk ASC');
//try/catch might make more sense as fetchAll() returns an object or an exception.
$result = $table->fetchAll($select)
return $result->toArray();
}
Change fetchRow() to fetchAll(). fetchRow() returns one row object or null, fetchAll() returns a rowset object (array of row objects) or an exception/fatal error.
if ($row = $table->fetchRow($select)) {
return $row->toArray();
}
change that portion of code to
return $your_database_object->fetchAll($select);
Related
Is there a way to get the value of a codeigniter db result object single value into a variable with 1 command?
I've been doing this:
$course_progress_object = this->training_model->get_course_progress($course_id,$user_id);
$course_progress = $course_progress_object[0]->progress;
Can we do it in a single command?
get_course_progress
public function get_course_progress($course_id, $user_id) {
$this->db->select('progress');
$course_object = $this->db->get_where('training_stats', array('course_id =' => $course_id, 'user_id ' => $user_id));
return $course_object->result();
}
I cant find out and tried many things?
In Model:
public function get_course_progress($course_id, $user_id)
{
$this->db->select('progress');
$course_object = $this->db->get_where('training_stats', array('course_id =' => $course_id, 'user_id ' => $user_id));
$row = $course_object->row();
return $row;
}
In Controller:
$course_progress_object = $this->training_model->get_course_progress($course_id,$user_id);
$course_progress = $course_progress_object->progress;
I have a query in ZF2 like following:
public function BrandWallBrandsById($userId,$brandId,$startDate,$endDate)
{
$select = new Select();
$select->from(array('p' => $this->table), array('id'));
$select->join(array('b' => 'brands'), 'p.brandId = b.id', array('id','name', 'cover', 'slogan', 'startDate', 'homepage'));
$select->columns(array(new Expression('SUM(p.points) as points'), "userId", "brandId"));
$select->order("p.points desc");
$select->group("p.brandId");
$where = new Where();
$where->notEqualTo("p.points", 0);
$where->equalTo("p.userId", $userId);
$where->equalTo("p.brandId", $brandId);
$where->between("p.time", $startDate, $endDate);
$select->where($where);
return $this->historyTable->selectWith($select)->toArray();
}
Since I'm returning only a single object, can I return an object from this query instead of an array[0] ?? Is there any way to do this ?
If you're expecting a signle row from your query then you can use current(). Modify the last line of your code, juste like this:
$row = $this->historyTable->selectWith($select)->current();
if(!$row){
throw new Exception('No row found');
}
return $row;
I'm a little bit baffled by this, so I'm hoping someone can shed some light on it for me.
I have a function which is meant to return a column Status from one of my tables, visit.
function someFunction($visitId = null) {
$visit = VisitQuery::create()
->select(array('Status'))
->findPk($visitId);
}
If I var_dump($visit), when calling the function for the first time, it outputs:
string '1' (length=1)
Subsequent, identical calls to the function however seem to return an entire object:
object(Visit)[30]
protected 'startCopy' => boolean false
protected 'id' => int 362
protected 'job_id' => int 351
protected 'company_id' => int 2
protected 'type_id' => int 1
protected 'visit_date' => string '2013-08-23 00:00:00' (length=19)
protected 'status' => string '1' (length=1)
...
I'm calling the function for the first time with an (int) $visitId passed via a posted form:
var_dump($visitId); // int 362
Subsequent calls are made with an (int) $visitId which is returned from another function, saveVisit() (which uses Propel to save the record - I believe this may have something to do with it).
$visitId = saveVisit($visitId);
var_dump($visitId); // int 362
I tried to do some debugging, and for some reason the query issued to MySQL is different between the first function call and subsequent ones:
var_dump($con->getLastExecutedQuery());
SELECT visit.STATUS AS "Status" FROM `visit` WHERE visit.ID=362 // 1st call
SELECT `ID`, `JOB_ID`, `COMPANY_ID`, `TYPE_ID`, `VISIT_DATE`, `STATUS`, `REMIND`, `PRINTED` FROM `visit` WHERE `ID` = 362 // 2nd call
SELECT `ID`, `JOB_ID`, `COMPANY_ID`, `TYPE_ID`, `VISIT_DATE`, `STATUS`, `REMIND`, `PRINTED` FROM `visit` WHERE `ID` = 362 // 3rd call
Can anyone tell me why or how this is happening?
I'm using Propel 1.6.
Propel's create() method:
public static function create($modelAlias = null, $criteria = null)
{
if ($criteria instanceof VisitQuery) {
return $criteria;
}
$query = new VisitQuery();
if (null !== $modelAlias) {
$query->setModelAlias($modelAlias);
}
if ($criteria instanceof Criteria) {
$query->mergeWith($criteria);
}
return $query;
}
Propel's findPk() method:
public function findPk($key, $con = null)
{
if ($con === null) {
$con = Propel::getConnection($this->getDbName(), Propel::CONNECTION_READ);
}
// As the query uses a PK condition, no limit(1) is necessary.
$this->basePreSelect($con);
$criteria = $this->isKeepQuery() ? clone $this : $this;
$pkCols = $this->getTableMap()->getPrimaryKeyColumns();
if (count($pkCols) == 1) {
// simple primary key
$pkCol = $pkCols[0];
$criteria->add($pkCol->getFullyQualifiedName(), $key);
} else {
// composite primary key
foreach ($pkCols as $pkCol) {
$keyPart = array_shift($key);
$criteria->add($pkCol->getFullyQualifiedName(), $keyPart);
}
}
$stmt = $criteria->doSelect($con);
return $criteria->getFormatter()->init($criteria)->formatOne($stmt);
}
My function to retrieve the visit status:
function getVisitStatus($visitId = null) {
if (empty($visitId)) {
return false;
}
try {
$visit = VisitQuery::create()
->select(array('Status'))
->findPk($visitId);
} catch (Exception $e) {
echo $e->getMessage(); exit;
}
if (is_null($visit)) {
return false;
}
return $visit;
}
The function which saves a visit record:
function saveVisit($data = null) {
if (empty($data)) {
return false;
}
try {
$visit = (!empty($data['visit_id'])) ? VisitQuery::create()->findPk($data['visit_id']) : new Visit();
if (!is_object($visit)) {
return false;
}
$visitDataMap = array(
'JobId' => 'job_id',
'TypeId' => 'type_id',
'VisitDate' => 'visit_date',
'Status' => 'status',
'CompanyId' => 'engineer_id',
'Remind' => 'remind'
);
$visitData = array();
foreach ($visitDataMap as $column => $value) {
if (!empty($data[$value])) {
$visitData[$column] = $data[$value];
}
}
$visit->fromArray($visitData);
$visit->save();
return $visit->getId();
} catch (PropelException $e) {
echo $e->getMessage(); exit;
}
}
It seems that on the first call will grab your data but then put a copy of the full object in to the instance pool. I am not sure if this is a bug or valid behaviour (your code would suggest the former, but I'd love to hear from someone who knows more about Propel such as a dev) but you can stop it happening with:
VisitPeer::clearInstancePool();
Bear in mind you're losing a bit of caching from other queries you might have done here with the visit relation.
You will be able to confirm this by adding an echo in the BaseVisitPeer.php file. You will see something like this:
public static function getInstanceFromPool($key)
{
if (Propel::isInstancePoolingEnabled()) {
if (isset(VisitPeer::$instances[$key])) {
return VisitPeer::$instances[$key];
}
}
return null; // just to be explicit
}
If you add an echo somewhere inside the if (isset(VisitPeer::$instances[$key])) { statement, you should see it appear only after the second and subsequent calls. If you were to comment this whole if statement out then you would get the same result back each time - the one you correctly get back from your original call.
Hope that helps!
I have the following model that print_r shows Array ( [id] => 1 [cms_name] => Content Mangement System ) Currently in my controller I have $data['contentMangement'] = $this->model->function but I am unsure how to bring my above array into this.
function systemOptions($options)
{
$this->db->select($options);
$query = $this->db->get('options');
if($query->num_rows() > 0)
{
$row = $query->row_array();
$row['cms_name'];
}
print_r($row);
return $query->result_array();
}
If you want all of your options you can do this:
function systemOptions($options)
{
$this->db->select($options);
return $this->db->get('options')->result_array();// will return empty array if there are no results
}
Or if you just want the first row (which is what it looks like from your question) you can do this:
function systemOptions($options)
{
$this->db->select($options);
$result = $this->db->get('options')->result_array();
if(!empty($result))
{
return $result[0];
}else{
return null; //or false or array(), or whatever you want
}
}
I'm trying to get a database query which is an object converted to an associative array, so that I can use it in the calendar class in codeigniter.
This is my model:
<?php
class Get_diary_model extends Model {
function getAllDiaries($year,$month) {
$data = $this->db->query("SELECT day AND entry FROM diary WHERE month=$month AND year=$year"); // the entries for the relevant month and year
foreach($data->result_array() as $row) { // return result as assoc array to use in calendar
echo $row['day'];
echo $row['entry'];
}
return $data;
}
}
and this is the error I get:
atal error: Cannot use object of type CI_DB_mysql_result as array in C:\wamp\www\mm\system\libraries\Calendar.php on line 219
Any ideas?
Check ou this video tutorial, it will help you -> http://net.tutsplus.com/tutorials/php/codeigniter-from-scratch-the-calendar-library/
Your model should look like this:
function getAllDiaries($year,$month)
{
$q = $this->db->query("SELECT day AND entry FROM diary WHERE month=$month AND year=$year");
if($q->num_rows() > 0):
foreach($q->result() as $row):
$data[] = $row;
endforeach;
return $data;
else:
return false;
endif;
}
and your controller:
function index($year = null, $month = null)
{
$this->load->model('Get_diary_model');
if (!$year) {
$year = date('Y');
}
if (!$month) {
$month = date('m');
}
$data['calendar'] = $this->Get_diary_model->getAllDiaries($year, $month);
}
The problem was not in your use of result_array(), more that you later return $data directly. $query = $this->db->query() then use $query->result_array() in the foreach. Then you can return $data after building it up in the foreach.
The other answer is a long-winded way of writing the following:
function getAllDiaries($year,$month)
{
$sql = "SELECT day AND entry FROM diary WHERE month=$month AND year=$year";
return $this->db->query($sql)->result();
}
But of course that will return an array of objects, not an multidimensional array.
Use below simple method,
$query = $this->db->get_where('table', array('table_id' => $id));
$queryArr = $query->result();
foreach ($queryArr[0] as $key=>$val)
{
$row[$key]=$val;
}
print_r($row); //this will give associative array
Here is the solution for CodeIgniter-3
function getAllDiaries(){
$query = $this->db->query("YOUR QUERY HERE");
return $query->result('array');
}
OR
function getAllDiaries(){
return $this->db->query("YOUR QUERY HERE")->result('array');
}
Note: result() function accept "array" or "object" as parameter. Default is "object"