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;
Related
I need to print $data2['hasil2'] result, but the result just print empty array Array ( ). Could anyone tell me how the correct way to passing $data1 and $semester in tampilSos function?
public function insertOrtu(){
$Semester= $_POST['Semester'];
$person=$this->session->userdata('idperson');
$data1=$this->M_Ortu->tampilIdsiswa($person);
$data2['hasil2']=$this->M_Ortu->tampilSos($data1, $Semester);
print_r($data2['hasil2']);
}
here my model
public function tampilIdsiswa($person){
$this->db->select('idsiswa');
$this->db->from('siswa a');
$this->db->join('siswa_kelas b','a.induk=b.induk','left');
$this->db->where('idperson',$person);
$data=$this->db->get();
return $data->row()->idsiswa;
}
public function tampilSos($idsiswa, $semester){
$array = array('idsiswa' => $idsiswa, 'kdSemester' => $semester, 'kdmapel'=>'sos');
$this->db->select('*');
$this->db->from('nilai_siswa a');
$this->db->join('master_nilai b','a.idnilai=b.idnilai','right');
$this->db->where($array);
$data = $this->db->get();
return $data->result();
}
I'm trying to build a query based on URL parameters. When the Controller is loaded I need to check which parameters have been provided and build a query from them. It's working with static values, but isn't working with conditional statements. Is my laravel syntax correct?
class OrdenesController extends BaseController {
public function showOrdenes($action)
{
$my_id = Auth::user()->id;
$my_cod = Auth::user()->codprov;
switch ($action)
{
case 'list':
$rows = DB::table('ordens')->count();
if(Input::get("jtSorting"))
{
$search = explode(" ", Input::get("jtSorting"));
$numorden= Input::get("nro_orden");
$filtros =explode(" ", $filtros);
$data = DB::table("ordens")
->select(array('*', DB::raw('SUM(cant_pend) as cant_pend'), DB::raw('SUM(importe) as importe')))
->where('cod_prov', '=', $my_cod)
->where('nro_orden', '=', $numorden)///work
---------- ////no work
if (Input::has('nro_orden')) {
->where('nro_orden', '=', $numorden)
}
---------- /// no work
->groupBy('nro_orden')
->skip(Input::get("jtStartIndex"))
->take(Input::get("jtPageSize"))
->orderBy($search[0], $search[1])
->get();
}
return Response::json(
array(
"Result" => "OK",
"TotalRecordCount" => $rows,
"Records" => $data
)
);
break;
};
}
}
You are missing the variables, no? You haven't told PHP what variable/object to do the where() to in your condition. The magic of Laravel's Eloquent (and a lot of other libraries) is that when you call its methods, it returns itself (the object) back so you can make another method call to it right away.
So when you do this:
$data = DB::table("ordens")
->select(...)
->where(...);
is the same as:
$data = DB::table("ordens");
$data = $data->select(...);
$data = $data->where(...);
But you are trying to do ->where(...) right away after if condition. You need to tell PHP which object/variable you are trying to call the method from. Like this:
$num = Input::get("nro_orden");
$data = DB::table("ordens")
->select(array('*', DB::raw('SUM(cant_pend) as cant_pend'), DB::raw('SUM(importe) as importe')))
->where('cod_prov', '=', $my_cod);
if (Input::has('nro_orden')) {
$data = $data->where('nro_orden', '=', $num);
}
$data = $data->groupBy('nro_orden')
->skip(Input::get("jtStartIndex"))
->take(Input::get("jtPageSize"))
->orderBy($search[0], $search[1])
->get();
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);
I'm using ActiveRecord in my app. I need to add many objects by attribute. Currently I do it as follows:
foreach($objects as $object):
$result += $object->value;
endforeach;
But it is very slow. I think I could get the same result but more efficient by sql sum(), so de question is can ActiveRecord return me the sum() result?
The only aggregating function already implemented in the model is count(). For sum(), you'd have to use an SQL query. You can do that using different classes (Connection, Table or Model).
Here's using find_by_sql() of the Model (returns an array of models):
$result = FooModel::find_by_sql('SELECT SUM(`value`) AS sum FROM `foo_table`')[0]->sum;
Add custom model to your lib/Model.php file
public static function sum($args) {
$args = func_get_args();
$options = static::extract_and_validate_options($args);
$options['select'] = 'SUM('.$args[0]["sum"].')';
if (!empty($args) && !is_null($args[0]) && !empty($args[0]))
{
if (is_hash($args[0]))
$options['conditions'] = (isset($args[0]["conditions"]) ? $args[0]["conditions"] : array());
else
$options['conditions'] = call_user_func_array('static::pk_conditions',$args);
}
$table = static::table();
$sql = $table->options_to_sql($options);
$values = $sql->get_where_values();
return static::connection()->query_and_fetch_one($sql->to_s(),$values);
}
Then call it:
YourModel::sum(array('conditions' => 'userid = 3', 'sum' => 'your_column'));
or
YourModel::sum(array('sum' => 'your_column'));
Using the following:
$last_book = tz_books::getLast($request->db, "WHERE book_id='{$request->book_id}'");
I get the following php object array,
[0] => tz_books Object
(
[db:tz_books:private] => com Object
[id] => 64BEC207-CA35-4BD2
[author_id] => 4F4755B4-0CE8-4251
[book_id] => 8FC22AA0-4A60-4BFC
[date_due] => variant Object
)
I then want to use the author_id, but for some reason it's not working.
Trying to use:
$tz_books->author_id;
Using print_r($last_book); prints the array to the console just fine. And Doing the following just to see if the correct variable was being used:
$author = $tz_books->author_id;
print_r($author);
Nothing is printed to the console, and even after digging through the php manual and trying a lot of alternatives, I can't seem to grab that variable. I'm hoping i'm making a rookie mistake and overlooking something stupid. Thank you for any help!
Edit: Class definition
private $db;
public $id;
public $author_id;
public $book_id;
public $date_due;
public function __construct($db, $values=null) {
$this->db = $db;
if ( $values != null ) {
foreach ( $values as $var => $value ) {
$this->$var = $value;
}
}
}
public static function retrieveAll($db, $where='', $order_by='') {
$result_list = array();
$query = 'SELECT '.
'id, '.
'author_id, '.
'book_id, '.
'date_due '.
"FROM tz_books $where $order_by";
$rs = $db->Execute($query);
while ( !$rs->EOF ) {
$result_list[] = new tz_books($db, array(
'id' => clean_id($rs->Fields['id']->Value),
'author_id' => clean_id($rs->Fields['author_id']->Value),
'book_id' => clean_id($rs->Fields['book_id']->Value),
'date_due' => $rs->Fields['date_due']->Value,
));
$rs->MoveNext();
}
$rs->Close();
return $result_list;
}
Your result object seems to be an array of books with 1 element.
Try
echo $tz_books[0]->author_id;
BTW, it also looks like you're escaping input by putting single quotes. This is not a reliable/recommended method. Use a database-specific escape function like this