I just want to ask if you can select a certain table in the database? There is this code in my
model:
public function select_tables(){
$tables = $this->db->list_tables();
return $tables;
}
and in my controller:
public function maintenance(){
$this->data['title'] = "Inventory Maintenance";
$this->load->vars($this->data);
$this->load->view('homeview');
$selecttable['tablename'] = $this->inventory_model->select_tables();
$this->load->view('maintenance_view', $selecttable);
$this->load->view('footer_view');
}
Here is the printscreen in my view:
There is the list of my tables in the database, what I want is I can only show limited tables, for example I just want to show "tbladditional, tblemployees, tblinventorytype". Is there a syntax where I can select a certain table? An equivalent to this syntax
"Select * from 'tablename' where 'tablename' = 'something'"
It's so confusing so please I really need your help. Thank you so much!!
public function select_tables(){
$tables = $this->db->list_tables();
$req_tables = array("tble1", "table2"); //pass your table names as Array
$tables = array_intersect($tables, $req_tables);
return $tables;
}
This is the programmatic way I can come with. As CI doesn't have any method to retrieve specific table names.
you can put a mixture of Codeigniter and the query result
For example:
$table_list = $this->db->list_tables();
foreach($table_list as $tl)
{
if(strpos(strtolower($tl),'tbladditional')==true ||
strpos(strtolower($tl),'tblemployees')==true ||
strpos(strtolower($tl),'tblinventorytype')==true)
{
$query = "Select * from $tl";
}
}
Related
I have a problem on getting multiple data of a single patient. I can only generate 1 physical examination result and I can't get all of it.
My Controller
public function print_sum_report($case_id){
//fetching all data from different tables
$case_id = 1;
$postnatal_id = 1;
$this->load->model('Prms_model');
$data['n_status'] = $this->Prms_model->get_status_f($case_id);
$data['n_mh'] = $this->Prms_model->get_mh_f($case_id);
$data['n_pe'] = $this->Prms_model->get_pe_f($case_id);
$data['n_post'] = $this->Prms_model->get_pn_f($postnatal_id);
$data['n_infant'] = $this->Prms_model->get_infant_f($case_id);
$this->load->view('report/reportsum', $data);
// print_r($data);
}
My Model
public function get_pe_f($case_id){
// joining 2 tables (physicalexamination and patient_info by ID)
$this->db->select('*');
$this->db->from('physicalexamination');
$this->db->where('case_id', $case_id);
$this->db->join('patient_info', 'patient_info.patient_ID = physicalexamination.Patient_ID');
$query = $this->db->get();
return $query->result();
}
$data['n_pe'] is a result object which contains many rows. You need to iterate over it to gather all the rows:
foreach($data['n_pe'] as $pe) {
var_dump($pe);
}
Also, you could write your model this way:
public function get_pe_f($case_id) {
// joining 2 tables (physicalexamination and patient_info by ID)
return $this->db
->where('case_id', $case_id)
->join('patient_info', 'patient_info.patient_ID = physicalexamination.Patient_ID');
->get('physicalexamination')
->result();
}
i have a select field named categories[] with multiple select and i written one on change function so on change fuction it will go the controller as an array of id's now what i want is i want to select foods from mysql table with these categories
<select name="categories[]">
<?php
foreach ($category as $c) {
?>
<option value="<?php echo $c->category_id; ?>"><?php echo $c->category_name;?></option>
<?php
}
?>
</select>
controller
public function get_foods(){
$categories = $this->input->post(NULL,true);
$sql = $this->subscription->get_foods($categories);
$result = array(
'result' => $sql
);
echo json_encode($result);
}
and model
public function get_foods($id){
$sql = "SELECT * FROM food_category fc
LEFT JOIN food f ON fc.food_id=f.food_id
WHERE f.food_status = 1 AND
fc.category_id = $id
ORDER BY f.food_id DESC";
$query = $this->db->query($sql);
return $query->result_array();
}
i want to fetch all the foods in these categories, so i think i should have to use some multiple where condition ?
You just need to store category with each food and when you get the foods you can use a where condition :
$this->db->where('category',$category);
use the where columns in () sql function for this.
for detail description on it. find here
http://www.w3schools.com/sql/sql_in.asp
If this can help, I think you need to post the categories one by one, then get it and put it in one array. Here is a code that may help
public function get_foods()
{
$result = array();
foreach($this->input->post('categories') as $c)
{
$result[] = $this->subscription->get_foods($c);
}
echo json_encode($result);
}
and for the model I suggest making use of AR of CI
public function get_foods($category)
{
$this->db->select('*');
$this->db->from('food_category as fc');
$this->db->join('food as f','fc.food_id = f.food_id','left');
$this->db->where('f.food_status', '1');
$this->db->where('fc.category_id',$category);
$query = $this->db->get();
return $query->result_array();
}
First we make an empty array, then using the foreach in post we get all the foods per category then return them inside the result array.
Hope this helps and if there's any error in the sql since I may have forgotten some of the join, I'd be willing to help again.
I have tried to get all column names from a table Teller
Function:
public function getTableColumns($tables)
{
return DB::select(DB::raw('SELECT
COLUMN_NAME,
DATA_TYPE,
COLUMN_DEFAULT
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
table_name = `Teller`'));
}
You can get all columns name by simply doing that...
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
public function getTableColumns($table)
{
return DB::getSchemaBuilder()->getColumnListing($table);
// OR
return Schema::getColumnListing($table);
}
Get Table Name From Model
$product = new Product;
$table = $product->getTable();
print_r($table);
Get Table Column Name From Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public function getTableColumns() {
return $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable());
}
}
Now you will get all columns of "products" table and if you need it in controller then you can get it by following way :
$product = new Product;
$columns = $product->getTableColumns();
print_r($columns);
Just in-case if you have multiple databases connections, try following:
Add in the top of your php script
use Illuminate\Support\Facades\Schema;
Retrieve anywhere in your code
With Database Connection
$columns = Schema::Connection('business')->getColumnListing('users'); // 'business' is your database connection
echo "<pre>";
print_r($columns);
exit();
Without Database Connection
$columns = Schema::getColumnListing('users');
echo "<pre>";
print_r($columns);
exit();
You only need extract the keys from the query response
array_keys(json_decode(json_encode($table[0]), true))
As of Laravel 6.x this works:
$db = DB::connection()->getPdo();
$rs = $db->query('SELECT * FROM Teller LIMIT 0');
for ($i = 0; $i < $rs->columnCount(); $i++) {
$col = $rs->getColumnMeta($i);
$columns[] = $col['name'];
}
print_r($columns);
The hint here is just to go around eloquent (which should just provide a simple way to do this, but clearly does not) and grab the PDO object and then use the answer from the same question for straight PDO access
This will also work when there is no database selected by replacing 'Teller' with databasename.Teller
HTH,
-ft
Another way from a model using collections.
collect(User::first())->keys();
#Eduardo Wallace method has it simplest; just return the first value from the table, strip off the values leaving the keys
$T1 = table_name::first();
$table_columns = array_keys(json_decode($T1, true));
If you don't need all the columns, strip away unneeded columns, leaving only the ones needed:
$needed_columns = array_diff($table_columns, ['unneeded_1', 'unneeded_2']);
You can argue the method used, simplest to me anyways!
$db = [];
$tables = DB::select('SHOW TABLES');
foreach ($tables as $key => $table) {
$name = $table->Tables_in_app;
$app[$name] = DB::getSchemaBuilder()->getColumnListing($name);
}
return $db;
You can get an idea with this script
$columns = array();
foreach(\DB::select("SHOW COLUMNS FROM $table") as $column)
{
//print_r($column);
$columns[$column->Field] = '';
}
return $columns;
in 12.17.22 it's
extremely simple
$columns=Schema::getColumnListing('my_table_name');
//e.g. your table's name is 'my_table_name' or 'Teller' or 'posts'
// and then
$fetchedSet= Post::select($columns)->where('sender_id','>',100)->get();
And you are done
You could simply write:
public function getTableColumns($tables)
{
return DB::select(
DB::raw('SELECT * FROM `Teller`')
);
}
If you have a Teller model you can also use Teller::all();
Update
To get all column name you can run SHOW FIELDS Teller
You can use this
DB::table('table_name')->get();
i have an problem. I have two tables:
1 called 'Offers'
1 called 'Networks'
In the 'Offers' table i have an field called 'NetworkId' and in my table 'Networks' i have an list of all networks with fild 'Id' and 'Name'.
I have an method in my Model to get all the rows in table 'Offers'. What i want know is how can i get the value of field 'Name' located in table 'Networks' using the 'NetworkID' that i grab with my method in my model.
I need create an new method ? create function ? idk what to do.
this is my controller atm:
public function index()
{
// Get List of the Offers
$this->load->model('offers_model');
$data['results_offers'] = $this->offers_model->list('all');
$this->load->view('offers_home', $data);
}
and this is my model code:
function list($id){
if($id != "all")
{
$query = $this->db->get_where('offers', array('offerid' => $id));
}
else
{
$query = $this->db->get('offers');
}
return $query->result();
}
Thanks for help me!
Try this
function getAllOffers(){
$query = $this->db->select('a.fieldname, b.name')->from('offers as a')->join('networks as b','a.networkid = b.id')->get();
return $query->result_array();
}
Further Information check Active Record
In my CodeIgniter project I'm getting the list of projects and successfully output them on a page. However, the data in one of the columns on that page should be retrieved from a different table in DB using the project ID. Could anybody help me to figure out how that can be done? Basically I need to make another query to that other table specifying the project id but don't actually know how to do that with CodeIgniter.
UPDATE
In the model I'm getting the list of projects with the following function:
function get_projects_list($page, $limit){
$sql = sprintf("SELECT * FROM Project WHERE deleted != 1 LIMIT %d, %d", ($page-1)*$limit, $limit);
$query = $this->db->query($sql);
return $query->result();
}
And in the controller I call the following function:
$projects_list = $this->Project_management_model->get_projects_list($curPage, self::$LIMIT_PER_PAGE);
$data['projects_list'] = $projects_list;
$data['cur_page'] = $curPage;
$data['page_count'] = $pageCount;
$this->load->view('project_management_view', $data);
And in the view I simply run on the $data with foreach and list the results in a table. In that table there's a column where I need to show a result from another table based on the ID of the project of that very row.
Thanks for helping.
You didn't mention whether you are using ActiveRecord or not. I am assuming that you are. I'll also guess that maybe what you need to do is use a JOIN.
If you were using straight SQL, you would do this using some SQL that might look something like this:
SELECT a.appointment_time, u.user_real_name FROM appointment a, site_user u WHERE u.site_user_id = a.user_id;
That would pull the user's name from the user table based on the user id in the appointment table and put it with the appointment time in the query results.
Using ActiveRecord, you would do something like this:
$this->db->select('appointment_time,user_real_name')->from('appointment')->join('site_user', 'site_user_id=appointment_user_id');
But why don't you tell us a little bit more about your question. Specifically, do you want this column in the other table to be related to the rows from the first table? If so, my JOIN suggestion is what you need.
I've actually found a way to do that with a custom helper. Creating a new helper and loading it in the controller gives an option to use the function from that helper in the view.
Thanks.
public function get data()
{
$this->db->flush_cache();
$query = $this->db->get('project_table');
$result = $query->result();
$data = array();
for ($i = 0;$i < count($result);$i++)
{
$data[$i] = $result[$i];
$data[$i]['project_data'] = temp($result[$i]->id);
}
return data;
}
private function temp($id = 0)
{
$this->db->flush_cache();
$this->where('id',$id);
$query = $this->db->get('project_table2');
$result = $query->result();
if (count($result) != 0)
return $result[0]->data;
}
you can do it by some thing like that,or you can use sub-query by query function of database.