at the moment I’m using these functions for my queries:
public function Surat_300() {
$query = $this->db->query(" SELECT * FROM `ts_300` WHERE `status_surat` = '1' ");
return $query->num_rows();
}
public function Surat_336_a() {
$query = $this->db->query(" SELECT * FROM `ts_336_a` WHERE `status_surat` = '1' ");
return $query->num_rows();
}
public function Surat_336_b() {
$query = $this->db->query(" SELECT * FROM `ts_336_b` WHERE `status_surat` = '1' ");
return $query->num_rows();
}
public function Surat_336_c() {
$query = $this->db->query(" SELECT * FROM `ts_336_c` WHERE `status_surat` = '1' ");
return $query->num_rows();
}
2
Answers
for this kind of scenario you’d use a variable (e.g.:
$table
) in your query string, to represent the table you are wanting the data from:this variable could be received in a controller as a $_POST variable from an input field or via ajax call, as $_SESSION variable, URL, etc.
since this is labeled Codeigniter, I’d suggest to take advantage of the framework using the following syntax to produce safer queries:
from a controller you’d call the model function this way:
Your four existing methods are retrieving all records from each table, just to return the row count. It would be much more efficient to use
SELECT COUNT(*) FROM `ts_300` WHERE `status_surat` = 1
instead.You could pass in the table name, as suggested by Vickel:
This feels a bit wrong, as these methods probably belong in their respective models anyway.
It’s not possible to be sure from your question, but it seems likely that these four tables contain data of the same structure, in which case
300
,336_a
,336_b
, etc should probably be values in a type identifier in a single table containing all of this data.