Join two tables with where clause using CodeIginter - php

I'm trying to load all the data from table "main_tests" where main_tests.id = test_name_price.test_id and where test_name_price.list_id = 1
I'm trying to do that but there it's just saying wrong syntax I'm beginner to CodeIginter Thanks For Advance
I have looked a lot for the answer but I couldn't get what I need exactly or either their ways don't work with me
here is my code
$result = $this->db->select('test_name_price.*, main_tests.*')
->from('test_name_price')
->where('test_name_price.list_id', 1)
->join('main_tests',
'test_name_price.test_id = main_tests.id')
->get();
if (count($result) > 0) {
foreach ($result as $itemsl) {
echo "
<option value='$itemsl->testname' data-code='$itemsl-
>test_code'>$itemsl->test_id</option>
";
}
}
echo "</select>"
EDIT :
that's the code in my controller , that view is addpatient
public function addpatient()
{
$this->load->model("khmodel","Khmodel");
$this->load->view('addpatient', array('result_array' =>
$result_array));
}
and here is my view
<?php foreach ($result_array as $key => $value) : ?>
<option value='<?= $value['testno'] ?>' data-code='<?=
$value['testno'] ?>'><?= $value['test'] ?></option>
<?php endforeach; ?>
and here is the MasterPage function I'm using to load the view , tell me if I need to add anything else
public function MasterPage($view='',$table='',$da='',$spg='',$szpg='')
{
if (!empty($table)) {
$data['result']=$this->Khmodel->get($table,$da,$spg,$szpg,"id
desc");
$data['pages']=$this->Khmodel->pagesno($table,$szpg);
}
$data['sview']=$view;
$data['index']=($view == 'home') ? '' : 'iner_page';
$getlang =$this->uri->segment(1);//$this->input->cookie('shlang', TRUE);
if($getlang=='en'){
$this->lang->load('en', 'en');
$data['lang']='en';
$data['nav_align']='right';
$data['xnav_align']='left';
}
else{
$this->lang->load('ar', 'ar');
$data['lang']='ar';
$data['nav_align']='left';
$data['xnav_align']='right';
}
//$this->load->view('main/close');
$this->load->view('main/header',$data);
if($view!='home'){
$this->load->view('main/top_header',$data);
}
$this->load->view('main/'.$view);
$this->load->view('main/footer',$data);
}

Well this what's worked with me like a charm !
I have used #Sherif Salah First Part of code INSIDE THE VIEW WITHOUT CONTROLLER OR MODEL
and It worked actually !!
Thanks for your Help
$table_one = 'test_name_price';
$table_two = 'main_tests';
$this->db->select("$table_one.*,$table_two.*");
$this->db->join($table_two, "$table_two.id =
$table_one.test_id", 'left');
$this->db->from($table_one);
$this->db->where("$table_one.list_id =
1");
$query = $this->db->get();
$result_object = $query->result();
if (count($result_object) > 0) {
foreach ($result_object as $itemsl) {
echo "<option value='$itemsl->tsprice' data-code='$itemsl-
>testno'>$itemsl->test</option>";
}
}

Here is how to join tables in codeigniter, but make sure that there are now similar field names or you have to select it individually and rename the field by hand.
$table_one = 'table_one_name';
$table_two = 'table_two_name';
$this->db->select("
$table_one.*,
$table_two.*
");
$this->db->join($table_two, "$table_two.id = $table_one.table_two_id", 'left');
$this->db->from($table_one);
$query = $this->db->get();
$result_object = $query->result();
$result_array = $query->result_array();
Note: if your code above is correct, you have to get the result as $result->result() as an object or $result->result_array() as an array.
Edit: Here is a quick example about how to use this array in your view, the above code will return array of arrays and you can process this array as:
<?php foreach ($result_array as $key => value) : ?>
<option value='<?= $value['name'] ?>' data-code='<?= $value['code'] ?>'><?= $value['id'] ?></option>
<?php endforeach; ?>
Note: please keep your logic in your controller, just pass the result to the view.
Edit: Lets keep it simple for now, supposingly your query worked fine and you can check for this by var_dump($result) so now you need to pass this data to the view however you wanna do it but supposingly AGAIN you got you result in the controller and all works fine, now you just have to pass it to the view like this:
$data = array("result" => $result);
$this->load->view('your_view', $data);
and in your view just loop through this array using the variable result or whatever you named it and that's it.
IMHO.. you should work through codeigniter's documentation and follow any step by step tutorial in codeigniter cause your problem is not that you don't know how to join two table, its about how to use the framework itself.

Related

Remove sql from html views use foreach?

Hello im hoping to move to mvc but im having trouble making templates, while i have most of it working im having trouble with queries inside foreach.
Normally i would pass $data (db-controller-view) and then i go through that data array in the html whats causing the headache is when i need to make another query inside that
passing another var in the data is easy its when i have to loop threw the first foreach result with another query if that makes sense only passed vars should be in html views.
I have also tried doing two foreach and trying to connect them together and knowing good practice would help ideally id like to have as many ways as possible to help with old procedural code
maybe a way to explain it is i have a getall model method now in a foreach in view how do i query the foreach result var outside the html this is also where linking two foreach or joining the results against each other
the code just shows a rough example and any help would be very appreciated
model
public function getFaqByCat(){
$stmt = $this->db->run("
SELECT `id`, `question`, `flag`
FROM `faq`
WHERE `type`=?
ORDER BY `order` ASC", ['categ']);
return $stmt;
}
public function getFaqByAnser(){
$stmt = $this->db->run("
SELECT `id`, `question`, `answer`, `flag`, `categ`
FROM `faq`
WHERE `type`=?
ORDER BY `order` ASC", ['item']);
return $stmt;
}
controller
$faq = $this->faqModel->getFaqByCat();
$faqtype = $this->faqModel->getFaqByAnswer();
$data = array(
'faqs' => $faq,
'faqtype' => $faqtype,
);
$this->view( 'faq/faqindex', $data );
view
<?php foreach ($data['faqs'] as $faq): { ?>
<h3> <?php echo $faq['id']; ?> </h3>
<?php echo $faq['type']; ?>
<?php echo $faq['question']; ?>
<!--THIS LINE GET EACH ANSER FOR EACH QUESTION-->
<?php foreach ($data['faqtype'] as $faq['question']): ?>
<?php var_dump($data['answer']); ?>
<?php endforeach; ?>
<?php } endforeach; ?>
This is unfortunately all over my project i am trying to update so better to start doing right from the start here is a average example of how it looks before update
foreach ($data['example'] as $row) {
// works from foreach
<?php echo $row["sender"]]);
// works from data
<?php echo $data["sender"]]);
// line below should be data not sql
$arr3 = DB::run("SELECT username FROM users WHERE id=?", [$row["sender"]])->fetch();
}

Tags system using "Toxi" solution CodeIgniter

First, i have three tables: video, tag and tagvideo. I already joined the three tables using left join.
My current objectives is to display list of related videos based on the current video tags. So far, i'm able to output the current video tags and trying to store in array where it will be used in the 'toxi' solution algorithm.
Although i followed the 'toxi' solution procedure, i still encountered errors: Object of class stdClass could not be converted to string, which it points to model($this->db->where_in('tag.tag_id', $result);) and for database: Not unique table/alias: 'video'.
I want to link the resulted tags with its video_id in the tagvideo table, Tagvideo table diagram
i already checked the inside of $result,an i assumed its already in array form.
By using this:echo '<pre>'.var_export($result, true).'</pre>'; exit;.
I follow the steps from this link: http://developer-paradize.blogspot.com/2013/12/how-to-display-search-results-with.html
Controller:
public function view($videoId)
{
if ($videoId == null)
{
redirect ('video/index');
}
else {
$videoDetails = $this->video_model->getVideoDetails($videoId);
$relatedVideo = $this->video_model->getRelated($videoId);
$data = array (
'videoDetails' => $videoDetails,
'relatedVideo' => $relatedVideo
);
$this->load->view('video/userdisplay' , $data);
}
}
Model:
public function getRelated($videoId)
{
//output the current video tags
$this->db->select('tag.tag_id');
$this->db->from('video','tagmap','tag');
$this->db->join('tagmap', 'tagmap.video_id=video.video_id','left');
$this->db->join('tag', 'tag.tag_id=tagmap.tag_id','left');
$this->db->where('tagmap.video_id', $videoId);
$query = $this->db->get();
if( $query->num_rows() > 0 )
{
$result = $query->result();
//show related videos based on the tags
$this->db->select('video.*');
$this->db->from('video','tagmap','tag');
$this->db->join('tagmap', 'tagmap.video_id=video.video_id','left');
$this->db->join('tag', 'tag.tag_id=tagmap.tag_id','left');
$tag_count = count($result);
$this->db->where_in('tag.tag_id', $result);
$this->db->group_by('video.video_id');
$count = "COUNT(video.video_id) =".$tag_count;
$this->db->having($count);
$query2 = $this->db->get('video');
return ($query2->num_rows() > 0) ? $query2->result() : FALSE;
}
else
{
return FALSE;
}
}
View:
<b>Related videos:<b>
<?php if (!empty($relatedVideo)): ?>
<?php foreach($relatedVideo as $item):?>
<?php echo $item->video_topic?>
<?php endforeach;?>
<?php else: ?>
<?php echo "No related videos." ?>
<?php endif; ?>enter code here

Extract CSV values from an array and display them Individually as a List

I have an array of CSV values in my Database like category1[obj1,obj2,obj3..]
View
<?php echo $row_company->category1;?>
Controller
$row_company = $this->employers_model->get_company_details_by_slug($company_name);
The employers_model then calls a procedure which in turn executes the required query which displays the contents of row = category1 in this fashion,
obj1,obj2,obj3...
I want to be able to show this result without the commas and as a list like this
obj1
obj2
obj3..
I'm Using CodeIgniter MVC Framework, I have some vague idea about the uses of implode function, and came across preg_split too, But don't know where to start meddling around from, the view or the controller.
Any direction towards the solution would be appreciated.
Edit : row_company in detail.
$row_company = $this->employers_model->get_company_details_by_slug($company_name);
if(!$row_company){
redirect(base_url(),'');
exit;
}
$company_website = ($row_company->company_website!='')?validate_company_url($row_company->company_website):'';
$data['row_company'] = $row_company;
$data['company_logo'] = $company_logo;
$data['company_join'] = $company_join;
$data['company_website'] = $company_website;
$data['company_location'] = $company_location;
$data['title'] = $row_company->company_name.' jobs in '.$row_company->city;
$this->load->view('company_view',$data);
}
employers_model content
public function get_company_details_by_slug($slug) {
$Q = $this->db->query('CALL get_company_by_slug("'.$slug.'")');
if ($Q->num_rows > 0) {
$return = $Q->row();
} else {
$return = 0;
}
$Q->next_result();
$Q->free_result();
return $return;
}
the procedure itself get_company_details_by_slug
BEGIN
SELECT emp.ID AS empID, emp.sts1, pc.ID, emp.country, emp.city, pc.company_name, pc.company_description, pc.company_location, pc.company_website, pc.no_of_employees, pc.established_in, pc.company_logo, pc.company_slug, pc.category1, pc.category2, pc.category3, pc.company_join
FROM `pp_employers` AS emp
INNER JOIN pp_companies AS pc
WHERE pc.company_slug=slug AND emp.sts1 ='active';END
Figured it out after referring many codeigniter/php forums.
Pretty simple actually,
<?php $array = explode(',', $row_company->category1);
foreach ($array as $item)
{
echo "<li>$item</li>";
}
?>
Thank you Nigel for pointing out to use explode function.
Cheers

A Foreach loop for a join table in Codeigniter

I am trying to build a dynamic subnavigation with Codeigniter. I have managed successfully to build a dynamic main navigation, but can't seem to manage to loop through the data from the joined table. In my code below i know i am not using the Foreach for the submenu correctly, but can somebody please help me or at least point me in the right direction.
Thank you a lot in advance
I am loading the foreach loops in the view like so
foreach ($query->result() as $row) {
$page_menu = $row->page_menu;
$page_menuName = base_url().$row->url;
//If page_menu is in database 1, show main menu item
if ($page_menu == '1') {
echo anchor($page_menuName, $row->page_headline)."<br/>";
}
}
if ($page_id == $webpage_id)
{
// I WANT THIS PART TO LOOP. THIS IS DATA FROM THE JOIN TABLE
foreach ($query->result() as $row) {
echo $subpage_id. "<--SUBID- " .$webpage_id. "<--- webpage id- ".$subpage_headline. "<--subheadline <br/><br/>";
}
}
This is the controller:
$this->load->module('webpages');
$query = $this->webpages->get_where_custom('url', $first_bit);
foreach ($query->result() as $row) {
$data['id'] = $row->id;
$data['headline'] = $row->headline;
$data['url'] = $row->url;
$data['content'] = $row->content;
$data['page_menu'] = $row->menu;
$data['sub_id'] = $row->sub_id;
$data['webpage_id'] = $row->webpage_id;
$data['sub_headline'] = $row->sub_headline;
}
And this is the model:
function get_where_custom($col, $value) {
$table = $this->get_table();
$this->db->where($col, $value);
$this->db->join('subpages', 'subpages.webpage_id = webpages.id', 'left');
$query=$this->db->get($table);
return $query;
}
My tables:
webpages
id,
headline,
title,
url,
content,
page_menu
subpages
sub_id,
subpage_headline,
subpage_title,
subpage_url,
subpage_content,
webpage_id,
sub_headnav
Your code:
if ($page_id == $webpage_id)
is not inside your foreach loop, is one thing. I know you say "i know i am not using the Foreach for the submenu correctly" but it's really hard for us to help you if you don't fix the bits you already know about before posting. No idea if what I said above is your problem or not

multilevel menu with codeigniter

i'm trying to create a multilevel list. I have two tables 'State' and 'City'. The city table has a foreign key 'state_id' which is the primary key of 'State' table. I want to show each state and under each state there is multiple cities. But when i run my code only the last stored state in the db and the cities under it show up. I want all the states in the Db and the cities corresponds to it to appear.
Part of my controller:
function index(){
$result = $this->db->count_all('state');
$id=1;
while ($id<=$result){
$data ['state'] = $this->state_model->stateid($id);
$data['city']=$this->state_model->statec($id);
$id++;
}
$this->load->view('state_view',$data);
}
The model:
function stateid($id = 0){
$this->db->where('id',$id);
$sql = $this->db->get('state');
return $sql->result();
}
function statec($id = 0){
$this->db->where('state_id',$id);
$sql = $this->db->get('city');
return $sql->result();
}
The view:
<?php foreach($state as $row):?>
<h4><?php echo $row->statename;?></h4>
<?php foreach($city as $row):?>
<?php echo $row->cityname; ?></br></br></br>
<?php endforeach;?></br></br>
<?php endforeach;?></br></br>
That is because in that while, with every iteration you overwrite the $data['state'] and $data['city']... so only the last iteration gets sent to the view.
You should look more into what arrays and especially multi-dimensional arrays work and how to use them.
That being said, you have bigger problems to consider. Like the code is very badly optimised and will cause problems later. Like your code assumes that the ids in the state table are consecutive, which is not necessarily true.
Here is a rought ideea what your code should look like:
model
function get_cities(){
$states = $this->db->get('state');
foreach ($states->result() as $state){
$cities = $this->db->get_where('city', array('state_id', $state->id));
$state->cities = $cities->result();
}
return $states;
}
controller
function index(){
$this->load->model('state_model);
$data['states'] = $this->state_model->get_cities();
$this->load->view('states/index, $data);
}
view:
<?php foreach($states as $state):?>
<h4><?php echo $state->statename;?></h4>
<?php foreach($state->city as $city):?>
<?php echo $city->cityname; ?>
<?php endforeach;?>
<?php endforeach;?>
Good luck

Categories