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
Related
I've started to code in April 2021 so I'm super new to this. Working on my final exam, I'd need your precious help! I want to generate a dynamic list from a database, containing 2 joined tables (users and interest). The 2 tables both contain "ID_user" which links them as a foreign key. The idea is that one the user is logged in, the profile page displays all the interests the user selected at sign up. At the moment I can only display the last interest selected and not all of them.
Here is my php:
$request2 = "SELECT `interest`.`name_Interest`
FROM `interest`
INNER JOIN `users`
ON `interest`.`ID_user` = `users`.`ID_user`
WHERE `pseudo` = '".$url_pseudo."'
";
$resultat2 = mysqli_query($connexion, $request2) or die (mysqli_error($connexion));
$nb_resultat2 = mysqli_num_rows($resultat2);
if ($nb_resultat2 > 0) {
while ($row = mysqli_fetch_array($resultat2)){
$name_Interest = $row["name_Interest"];
}
}
Here is the HTML displaying the response:
enter image description here
Here is my db:
enter image description here
Any idea why I can get only 1 value?
enter image description here
thanks in advance
Your while loop is writing to the same variable for each iteration of the loop;
while ($row = mysqli_fetch_array($resultat2)){
$name_Interest = $row["name_Interest"];
}
This will leave $name_Interest containing the last value from your database after the loop has completed.
To resolve this, you will need to keep a list of interest names - this can be achieved by using an array. PHP Array Documentation
// Declares the empty array
$interests = [];
// Loop through database results
while ($row = mysqli_fetch_array($resultat2)){
// Add this value to the array
$interests[] = $row["name_Interest"];
}
Now, $interests will hold all of the values from the database!
You will need to print these out differently in your HTML, by looping through all the values in the array and printing one at a time:
(PHP foreach documentation)
<ul>
<?php foreach ($interests as $interest) { ?>
<li><?php echo $interest; ?></li>
<?php } ?>
</ul>
Solution
Simple store all user interests on array and then show in iteration on page.
Code:
$user_interests=array();
while ($row = mysqli_fetch_array($resultat2)){
$user_interests[] = $row["name_Interest"];
}
Now $user_interests array holds all interests of users as a result of join.
At last loop over it
<?php foreach ($user_interests as $interest) { ?>
<p><?php echo $interest; ?></p>
<?php } ?>
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();
}
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.
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
I have a sidebar with categories. when i click on one categorie it shows me the factories who are located in that category.
I did this using joins in codeigniter.
Now i want to show how much factories are in a category. so for example:
Categories.
Cars (2)
Books (7)
Animals (45)
So it simple has to show how much factories have that specific category.
i tried to do a simple count_all_results but then i get the total count of factories. but i want them to count by the specific id of categories.
my model function:
function categorieen_getall($segment3)
{
$this->db->where('categorieen.idcategorieen', $segment3);
$this->db->select('*');
$this->db->from('bedrijfcategorieen');
$this->db->join('categorieen', 'categorieen.idcategorieen = bedrijfcategorieen.idcategorieen');
$this->db->join('bedrijven', 'bedrijven.idbedrijven = bedrijfcategorieen.idbedrijven');
$query = $this->db->get();
$result = $query->result();
/*
echo '<pre>';
print_r($result);
*/
return $result;
}
My controller function:
function get_All()
{
$data['cat'] = $this->categorieen_model->categorieen_getall($segment3);
$this->load->view('views/sidebar', $data);
}
My view:
<div id="sidebar">
<?php
echo '<h3>Categorieën</h3>';
echo ($this->db->count_all_results('categorieen'));
?>
<hr>
<br/>
<?php
echo '<ul>';
if(isset($cat) && is_array($cat)){
foreach($links as $k => $value){
echo '<li>';
echo '<br>';
echo '' .$value->Categorie. '';
echo '</li>';
}
}
echo '<ul>';
/*
if(isset($cat ) && is_array($cat )){
foreach($cat as $key => $row){
echo "Categorie:"; echo $row->Categorie;
echo "<br />";
echo $row->idcategorieen;
echo "<br />";
echo $row->Bedrijfsnaam;
}
}
*/
?>
</div>
My database scheme:
Factories
--------
idfactories
factoryname
adress
email
...
Categories
----------
idcategories
Category
Factorycategories
-----------------
idfactorycategories
idcategories
idfactories
This is not quite suitable because I know there is a better way to do this, but this will do the work for you:
// Get categories
$categories = array();
$query = $this->db->query("select * from `Categories` order by `idcategories`");
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
$query_count = $this->db->query("select `idfactorycategories` from `Factorycategories` where `idcategories` = {$row['idcategories']}");
$factory_count = $query_count->num_rows();
$categories[] = array(
'count' => $factory_count
);
}
}
For ease, you can first get categories in a foreach loop and then for each of them submit a query for the factories table to get relevant count of factories with that related category id.
I asked another question. with the same problem and i solved it.
Look at my own answer with the solution i got!
Count results in joined table and show between () in sidebar
Thanks for the people who helped me :)