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();
}
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 } ?>
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.
I am trying to return the number of results found on my page above an html table. I am using an mvc framework for the first time so it's very new to me how the process works.
My query works and displays the tabular results successfully, my issue is [probably] with the positioning of my return code?
I have included my code for reference;
Model
public function categoryView()
{
$sth = $this->db->prepare("SELECT
b.id,
b.title,
b.category,
FROM book
WHERE status != 'Archive' AND category = :cat ORDER BY id DESC LIMIT 15");
$sth->bindValue(':cat', $_GET['category']);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC); // won't run when included
return count($result); // won't run when included
$all_books = array();
foreach ($sth->fetchAll() as $book) {
$all_books[$book->id] = new stdClass();
$all_books[$book->id]->id = $book->id;
$all_books[$book->id]->title = $book->title;
$all_books[$book->id]->category = $book->cat_name;
}
return $all_books;
}
View
Found <?php echo count($result); ?> records
<table>
<?php
foreach ($this->books as $book) {
echo "<tr>";
echo '<td>'.$book->id.'</td>';
echo '<td>'.$book->title.'</td>';
echo '<td>'.$book->category.'</td>';
echo "</tr>";
}
?>
</table>
Controller
function categoryView()
{
$categoryView_model = $this->loadModel('Books');
$this->view->books = $categoryView_model->categoryView();
$this->view->render('books/categoryView');
}
I receive the error errors on my view page
Warning: `Invalid argument supplied for foreach() ... on line 51`
and
Found
Notice: Undefined variable: result in ... on line 47
0 records
Line 47 contains Found <?php echo count($result); ?> records
Line 51 contains foreach ($this->books as $book) { ... }
Any advice or help is appreciated.
Remove these two lines
$result = $sth->fetchAll(PDO::FETCH_ASSOC); // won't run when included
return count($result); // won't run when included
In your view change
Found <?php echo count($result); ?> records
to
Found <?php echo count($this->books); ?> records
The reason you have to do this is because you're storing the results returned from categoryView() into the books property of the view when you run the following line
$this->view->books = $categoryView_model->categoryView();
Note that the count will always be a maximum of 15. If you want to display the total # of found results you should issue a separate select count(*) without a limit clause.
It would help us a lot if you specified the framework. Honestly I have only worked in Zend as a php framework but over there you have to assign the property to your view:
$this->view->property = $all_books; //or any other property
and to retrieve it in the view
<?php echo $this->property; ?>
I find it hard to beleive that your MVC calls the function (action),which in zend needs to be named in a specific way, from the view and so uses a return. I an tell you one thing, your way of sending the variable to the view is wrong, the return must not be the correct way of sending it. Without your framework this is the only way I can help you in addition I would tell you to actually echo an isset f both variables and you will see my theory is right you are not sending the variables from the controller, action or function correctly
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
How could I best loop the data through a variable that's nested inside a 'while' loop but it's called outside of it ? Like in this example:
PHP:
$fr_q2 = mysqli_query($connect,"SELECT * FROM friends WHERE username ='".$_SESSION['user']."'
ORDER BY id DESC");
while ($rowsPicFr2 = mysqli_fetch_array($fr_q2)) {
$friends_q2[] = $rowsPicFr2['added_friend'];
$frn[] = $rowsPicFr2['added_friend'];
$frn2 = $rowsPicFr2['added_friend'];
}
$rowscheck = mysqli_num_rows($fr_q2);
for ($i=0; $i<$rowscheck; $i++)
HTML:
YES
So I need to pass $frn[$i] into a remdata() function - but the $frn[$i] needs to loop....All I get is a string of all ids from 'friend_added' in $frn[$i]....Thanks.
Once this HTML is sent to the browser, it won't loop anymore. It will just be HTML. So what you need to do, is either have it loop in JavaScript or simply echo each remdata():
YES
This solution is only really an option if you have very few elements in $frn.
Your question is confusing; I think you need the loop for the HTML output
<?php foreach ($frn as $i => $friend_id){ ?>
YES
<?php } ?>
Based on your comment in toon81's answer, it seems like you're having a problem dealing with several loops in your output that deal with the same result set in your database query. I'm not sure. I'd suggest in the future that you try to make your question easier to follow. For instance, do we need to know it's a social networking app? Your variable names aren't inherently easy to understand; what's the difference between $frn and $frn2? Presumably that's 'friend', but I keep reading it as 'fern'. You also only provided one line of your output, but your problem seems related to it's interaction with other output. Your code is cut off -- the rowscheck loop doesn't have a definition.
That said, this is a high level suggestion of how I'd handle your work differently. Data preparation:
$connection = ...;
$user = $_SESSION['user'];
$sql = "
SELECT added_friend
FROM friends
WHERE username = '$user'
ORDER BY id DESC
";
$response = mysql_query($sql, $connection);
$added_friends = array();
while ($row = mysql_fetch_object($response)){
$added_friends[] = $row->added_friend;
}
Ouput handling:
// With one loop if the markup can be ouput all at once.
foreach ($added_friends as $friend){
// Your 'friends_q2', whatever that is.
echo "Friends_q2: $friend";
// Your 'frn2' output, whatever that is.
echo "Frn2: $friend";
// Your 'frn' output.
echo "YES";
}
// ...or multiple loops if it can't.
foreach ($added_friends as $friend){
// Your 'friends_q2', whatever that is.
echo "Friends_q2: $friend";
}
foreach ($added_friends as $friend){
// Your 'frn2' output, whatever that is.
echo "Frn2: $friend";
}
foreach ($added_friends as $friend){
// Your 'frn' output.
echo "YES";
}
In any case, you're handling the same ID three times in different lists and in different ways. I'm not at all sure why. Is this what you're asking for help with?