codeigniter where with result not working - php

$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().....)

Related

Trying to get property of non-object php variable

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

codeigniter get db object result value into variable in a single command

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;

Laravel conditions in Controller where clause

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();

How make a Dynamic bindValue()?

Okay I have a function called sendQuery which sends your query.
I know how to do it with BindParams, but I can't really think of a way to make it work with bind values inside a execute.
This is the code:
public function sendQuery($query, array $value, $do_fetch)
{
$query_process = $this->db->prepare($query);
if(!$query_process->execute($binds))
{
throw new excpetion ("An error has occured!");
}
$this->insert = $this->db->lastInsertId();
$this->row_count = $query_process->rowCount();
if($fetch == true)
{
return $query_process->fetchAll();
}
}
As you see, it executes with $binds,
Works like (WHERE user = ?), but I want to send queries like this:
(WHERE user = :user) instead of a ' ? ', and multiple of them.
How do I do so?
You have to do exactly the same.
Just get rid of useless code and use consistent variable naming
public function sendQuery($query, array $binds, $do_fetch)
{
$stm = $this->db->prepare($query);
$stm->execute($binds);
$this->insert = $this->db->lastInsertId();
$this->row_count = $stm->rowCount();
if($do_fetch)
{
return $stm->fetchAll();
}
}
$sql = "SELECT * FROM t WHERE c1=:name AND c2=:age";
$param = array ("name" => $name,"age" => $age);
$data = $db->sendQuery($sql, $data, 1);
However, instead of just single function I would create a set of them:
query() to run non-select queries
getOne() preforms select and returns scalar value
getRow() returns a row
getAll returns all rows
it could be extremely handy

Where to check for any results

Ok so I have 2 classes. Photo class and PhotoMapper class.
Photo class contains all the values and outputs them.
PhotoMapper sets the values to the Photo class, by a assign class, like this:
$query = "SELECT * FROM users";
$query = $this->_pdo->prepare($query);
$query->bindValue(":id", $photo->id());
$query->execute();
$data = $query->fetch();
$photo->assign($data);
And the assign:
public function assign($data){
if (is_array($data)) {
foreach ($data as $name => $value)
{
$this->{'_' . $name} = $value;
}
}
}
Now where would i check for if $query->rowCount() > 0 ?
Should i inside is_array after the foreach, make a $this->rowCount = .. ?
What would be best to perform this check? I would like to check for the rowCount outside of both classes..
$photo = new Photo($albumID, $photoID, $view, $userID);
$photoMapper->select($photo, $view);
Is how it looks outside the classes. How can i check and output error if select(which is the query above) didnt find any rows?
I would need to have 2 queries? One to check, and one to select them? or?..
Well, if you're expecting data from the fetch operation but there isn't any (you could simply find out by checking if $data has any contents), you should throw an Exception. The following code snippet would typically be placed before the fetch:
// ...
$query->execute();
if ( !( $data = $query->fetch() ) ) {
throw new Exception('photo could not be loaded');
}
$photo->assign($data);
// ...
However, if you want the code to continue regardless, you can reverse the if condition, and put the assign call inside the statement;
$query->execute();
if ( ( $data = $query->fetch() ) ) {
$photo->assign($data);
}

Categories