I am using codeigniter and I have made a function to return name of the user. Here is the code:
$this->db->where('u_id', $id);
$query = $this->db->get('users');
$data = $query->result_array();
$string = $data->u_name.' '.$data->u_surname;
return $string;
When I am using this function i get this error:
Message: Trying to get property of non-object and recall the line with
$string = [...]
Use foreach loop:
foreach ($data as $row)
{
echo $string = $data['u_name'].' '.$data['u_surname'];
}
You can try like this.In codeigniter,The row() returns the matched first row according to your condition in object form.
$this->db->where('u_id', $id);
$query = $this->db->get('users');
$data = $query->row();//change here
$string = $data->u_name.' '.$data->u_surname;
//echo $string;
return $string;
for more see Codeigniter Result Sets
Try this code to return
$this->db->select('*');
$this->db->from('users');
$this->db->where(array('u_id'=>$id));
$query=$this->db->get();
if($query->num_rows()()>0)
{
$data = $query->result();
return $data->u_name.' '.$data->u_surname;
}
This is because the function you chose to generate results for you query.
$data = $query->result_array();
result_array() returns the results in an array even if you only had one result, so when you try to $data->u_name for instance, you have this error because the array does not have that property.
You can do a foreach on $data and perform your logic or use other methods to get the result from the query like $query->row_array();
Take a look on the codeigniter documentation: Generating Query Results
Related
I have this variable called $result = $request->data;
when I use something like this return $result; I can get sample output like this
["WLP001","WLP002","WLP003"]
I'm trying to use these values on whereIn function of laravel
Code
public function get_compare_data( Request $request ){
$result = $request->data;
$data = YeastModuleModel::whereIn('part_number', [$result])->get();
return $data;
}
But I'm getting internal server error 500
According to Laravel docs, https://laravel.com/docs/8.x/queries
The whereIn method verifies that a given column's value is contained within the given array.
$result is an array.
you should not put $result in another array.
$users = DB::table('users')
->whereIn('id', [1, 2, 3])
->get();
so you should change your code to:
public function get_compare_data( Request $request ){
$result = $request->data;
$data = YeastModuleModel::whereIn('part_number', $result)->get();
return $data;
}
hello everyone i write a codeigniter function to return data fro database
this is my function
public function get_total_results($filtering = false)
{
if ($filtering) {
$this->get_filtering();
}
foreach ($this->joins as $val) {
$this->ci->db->join($val[0], $val[1], $val[2]);
}
foreach ($this->where as $val) {
$this->ci->db->where($val[0], $val[1], $val[2]);
}
foreach ($this->or_where as $val) {
$this->ci->db->or_where($val[0], $val[1], $val[2]);
}
foreach ($this->group_by as $val) {
$this->ci->db->group_by($val);
}
foreach ($this->like as $val) {
$this->ci->db->like($val[0], $val[1], $val[2]);
}
if (strlen($this->distinct) > 0) {
$this->ci->db->distinct($this->distinct);
$this->ci->db->select($this->columns);
}
$query = $this->ci->db->get($this->table, null, null, false);
return $query->num_rows();
}
but i get an error of
An uncaught Exception was encountered
Type: Error
Message: Call to a member function num_rows() on boolean
in line of return $query->num_rows();
i don't know what is wrong with my code that i got this error so i know the error in last line in returning result any suggestion or idea
The problem is that the line
$query = $this->ci->db->get($this->table, null, null, false);
// Note: all you really need is $this->ci->db->get($this->table);
It is assigning the value false to $query. That usually happens when Query Builder creates a SQL statement that does not make sense - it happens.
You can see what Query Builder creates this way
// comment out the get() call
// $this->ci->db->get($this->table);
// run this instead
$sql = $this->db->get_compiled_select($this->table);
echo $sql;
// remove the comments once you see where the problem is
//return $query->num_rows();
You will probably be able to see where the SQL statement syntax is wrong and adjust your earlier code accordingly.
You might want to add a check of the get() return to your logic, e.g.
$query = $this->ci->db->get($this->table);
// Is $query truthy? (not false, null, etc)
if(! empty($query))
{
return $query->num_rows();
}
get() method of codeigniter have syntax like:
get([$table = ''[, $limit = NULL[, $offset = NULL]]])
Parameters: $table (string) – The table to query $limit (int) – The
LIMIT clause $offset (int) – The OFFSET clause
Returns: CI_DB_result instance (method chaining)
Return type: CI_DB_result
You have passed more than three parameters. So, Please check the parameters. It may resolve your problem.
Refer this for more information.
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();
$this->select("unm")->from("user")->where(array("age"=>20))->result();
not working, even any query including where.
Not able to use, result(), row() etc.
$rowSet=$this->select("unm")->from("user")->where(array("age"=>20));
$rowSet->result();
also not working
Fatal error: Call to undefined method CI_DB_mysql_driver::result() in C:\xampp\htdocs\ci\application\models\testModel.php on line 24
You didn't executed the query. Try with
$rowSet=$this->select("unm")
->from("user")
->where(array("age"=>20));
$rowSet = $this->db->get(); // this was missing
$query->result();
For Reference
Why don't you use a function like this?
public function getDataByID($id) {
$this->db->select ( '*' );
$this->db->from ( 'item' );
$this->db->where ( 'id', $id );
$query = $this->db->get ();
$row = $query->first_row ();
return $row;
}
Try this:
$where_array = array("age"=>20);
$result = $this->db->select('unm')
->from()
->where($where_array)
->get()->result();
print_r($result); gives you output in the following form
array([0]=>stdobj(),[1]=>stdobj().....)
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"