Making where clause dynamic in sql in CI - php

I want to display the content of page dynamically this following code is working fine but it only shows the content of specific id...how can i make that dynamic??
Model
public function getAllDepartment() {
$join = $this->db->query( "Select * from labreport_db inner join patient_db on labreport_db.P_ID=patient_db.id where labreport_db.P_ID=15");
return $join->result_array();
}
Controller
public function reportDisplay(){
$data['clubs'] = $this->labdoc_model->getAllDepartment();
$this->load->view('SystemAdminUser/labreport', $data);
}

There is simple work around for this using Query Builder class of CI.
So this is how your code will look like,
$id=15;
$this->db->select('*');
$this->db->from('labreport_db');
$this->db->join('patient_db', 'labreport_db.P_ID = patient_db.id');
$this->db->where('labreport_db.P_ID', $id);
$query = $this->db->get();
This is standard approach in CI to make database operation using query builder class in which you can perform dynamic WHERE condition.
For which just change the value of $id and the query will do the needful.
Reference: https://www.codeigniter.com/userguide3/database/query_builder.html#selecting-data

Hold the id in some variable like:
$pid = $_REQUEST['p_id'];
// $_REQUEST['p_id'] will contain the dynamic value in it
and put this variable in your query like:
where labreport_db.P_ID = $pid;
It will show the data for the value contained in $pid, and make sure it contains the dynamic value in it.

You can used this code for you solution.
Model.php
public function getAllDepartment($pId) {
$join = $this->db->query( "Select * from labreport_db inner join patient_db on labreport_db.P_ID=patient_db.id where labreport_db.P_ID=".$pId);
return $join->result_array();
}
Controller.php
public function reportDisplay(){
$pid = $_REQUEST['pid']; //OR $_GET['pid']; OR $_POST['pid']; You can pass your id for get content
$data['clubs'] = $this->labdoc_model->getAllDepartment($pid);
$this->load->view('SystemAdminUser/labreport', $data);
}

There are a couple of ways doing it. One of them is through CI routing ability.
Model
public function getAllDepartment($p_id = 0) {
$join = $this->db->query( "Select * from labreport_db inner join patient_db on labreport_db.P_ID=patient_db.id where labreport_db.P_ID={$p_id}");
return $join->result_array();
}
Comment: I added $p_id as a variable to fetch the ID dynamically.
Controller
public function reportDisplay($p_id = 0){
$data['clubs'] = $this->labdoc_model->getAllDepartment($p_id);
$this->load->view('SystemAdminUser/labreport', $data);
}
Comment: We also add a variable called $p_id in the reportDisplay function and pass it to your model's getAllDepartment()function.
How to fetch the report dynamically
I don't know your URL structure, but for example purposes let's say it's http://localhost/yourcontrollername/reportDisplay/
To access it dynamically, simply add an ID after the reportDisplay
For example:
http://localhost/yourcontrollername/reportDisplay/15
http://localhost/yourcontrollername/reportDisplay/10

Related

Yii2: How to filter fields of a find()->all functions?

I have to create a JSON with only two fields (id and name) with data from a table of my database.
I made a function inside my AnalysisController file of my Yii2 application:
public function actionAnalysis()
{
Yii::$app->response->format = Response::FORMAT_JSON;
$query = Analysis::find()->all();
return $query;
}
Then I tested it with http://localhost:8080/analysis/analysis and it works great. But it returns a lot of fields and I just need id and name field.
How can modify the actionAnalysis() function so it can filter the fields?
You can use select()
$query = Analysis::find()->select(['id','name'])->all();
OR
If you need an array asArray()
$query = Analysis::find()->select(['id','name'])->asArray()->all();
OR
You want to set up dropdown prefer column()
$query = Analysis::find()->select('name')->indexBy('id')->column();

how to reset default scope in yii2

I am using default scope in my project and it works fine.
public static function find()
{
return parent::find()->where(['is_deleted' => 0]);
}
But now, I want to show all the deleted records in the report section.
How can I skip default scope for particular query only?
Use this to clear or redefine your condition:
$model = Model::find()->where('');
If you want to make sure that you're using fresh query (without any params or conditions), you need to create new ActiveQuery object for given model.
$query = Yii::createObject(ActiveQuery::className(), [Post::class]);
Or add a helper method in model itself:
public static function freshFind()
{
return parent::find();
}
and use it instead of Post::find().
You could avoid the use of find() ..using a findBySql
$sql = 'SELECT * FROM product';
$product= Product::findBySql($sql,)->all();
in this way you all the models of product ..
and you could also use
$sql = 'SELECT * FROM ' . Product::tableName() ;
for avoid explici table name for Products

CakePHP, Query from Model

How I can execute a SQL query in CakePHP.
I want to make some like this code
$employees = $this->Employee->find('all');
but introducing my own SQL statment.
Insert into your Model a function that executes your SQL statment,
public function get_employees() {
$sql = 'select * from employees';
$data = $this->query($sql);
return $data;
}
And call this function like this way:
$employee = new Employee();
$data = $employee->get_employees();
In model you can't write model name. Its already detected. Use only
$this->find('all');
Assuming your statement is inside EmployeesController.php
$employeeRows = $this->employee->find('all', array('conditions'=>array('id' => 100)));
if you are in another controller, you have to load the model before the find
$this->loadModel('employee');
if you are in a view, you can write a helper and use raw sql
The cakephp website also offers the following controller logic
$this->Picture->query("SELECT * FROM pictures LIMIT 2;");

Does get_where() allow multiple parameters?

I am passing a parameter from model to view like this
Model
class school_model extends CI_Model{
function employee_get($student_id){
$query = $this->db->get_where('students', array('student_id'=>$student_id));
return $query->row_array();
}
}
Controller
function bret($student_id){
$this->load->model('school_model');
$data = $this->school_model->employee_get($student_id);
echo $data['student_gender'];
}
This obviously translates to select * from students where id=id given for example and seen through the browser like http://example.com/env/at/index.php/frontpage/bret/306
I am wondering if the get_where() is suitable if i wanted to have this query
select student_gender,student_has_a_medical_condition from students where (student_gender = 'female' && student_has_a_medical_condition = 'no') LIMIT 40;
Will i need to extend get_where() for it to work?.
First,I suggest reading the excellent documentation for CodeIgniter on the ActiveRecord class.
You don't have to extend get_where() but just use the existing methods to define your query:
function employee_get($student_id){
$this->db->select('student_gender','student_has_a_medical_condition');
$query = $this->db->get_where('students', array('student_id'=>$student_id,'student_has_a_medical_condition'=>'no','student_gender'=>'female'),40);
return $query->row_array();
}
Of course you can pass in the additional parameters to the function so they are not hardcoded, and you can also pass in the desired columns as a paremeter, too. But start with the documentation.

Adding additional data to select query result

I am fetching data from Articles table but I want to extend returned result with some data from another table.
For example:
public function getArticlesByCategoryId($category_id = 0) {
$select = $this->_db->select()
->from($this->_name)
->limit(5)
->order("pubDate DESC");
$result = $this->_db->fetchAll($select);
$mCategories = new Model_Categories();
foreach($result as $row) { // as &$row doesn't work
$category_name = $mCategories->getNameById($row["category_id"]);
$row["category_name"] = $category_name; // this to add to $result but dunno how
// blah blah...
}
return $result; // the new one with ...->category_name in it.
}
I hope you could understand what I am looking for.
Or maybe it is better to write a single query (with joins, don't know how) and fetch all the data needed in once without calling methods from another Models?
This indeed looks like you should use a join. This definitely is the easiest way to solve your problem. The following query would do the trick:
$select = $this->_db->select()
->from($this->_name)
->join('category_table', 'category_table.id = ' . $this->_name . '.category_id', array('category_name'))
->limit(5)
->order("pubDate DESC");
This will add the category name to the row.
In case you don't want to use a join, you can add a custom field to your row by using a custom row class. This however requires a bit more work. Create the class as follows:
class MyApp_Model_Row_MyRow extends Zend_Db_Table_Row_Abstract
{
public $categoryName;
}
Then you should indicate in your DbTable class that you want to use this new row class:
class MyApp_Model_DbTable_Articles extends Zend_Db_Table_Abstract
{
...
protected $_rowClass = 'MyApp_Model_Row_MyRow';
}
You can then set the category name in a fetched row.
To get all articles with data from your category table your query could look like:
$select = $this->_db->select()
->from($this->_name)
->joinLeftUsing('category','category_id', array('category_name'))
->order("pubDate DESC");
See also: http://framework.zend.com/manual/en/zend.db.select.html

Categories