I am new to codeigniter. I have successfully stored the data to database from view. Now thing is i want to retrieve the data from database and show it in the view. Anyone can help from another link or atleast tell me the flow of passing the data. I m working on a form with text fields and buttons
To retrieve the rows in questions, you want to do something like this:
$data['rows'] = $this->db->get_where('table_name')->result();
And then pass this variable to your view:
$this->load->view('index', isset($data)?$data:'');
And then access it:
var_dump($rows);
Here is an example of one of mine
Controller
$data['title'] = "title";
$this->db->select("title, content, date")->from("posts")->where('parent', $parent)->where('status', 'publish')->order_by("id", "asc");
$query = $this->db->get();
if($query->result()){
$data["mainContent"] = $query->result();
}
$this->load->view("pages/header/head", $data); //this sends the mysql to the page
$this->load->view("pages/van");
$this->load->view("pages/footer/footer");
View (this is for an unordered list
<?php foreach($mainContent as $row):?> Note maincontent above as well.
<ul>
<li> <?php echo $row->title;?></li>
<li> <?php echo $row->content;?></ul>
</ul>
<?php endforeach;?>
You would do the same for tables, or posts or whatever. The foreach will echo data until it runs out
Related
I want to store the list of data into session with single line and then how to extract that data on view.userData variable contains list of data.I can store the data like below that i know.but instead of writing multiple line can i store with single line.and how can i extract that data to use on view.Thanks in Advance.
$userData=$google_oauthV2->userinfo->get();
$this->session->set_userdata('userdata',$userData['id']);
$this->session->set_userdata('username',$userData['given_name'];
Can I store the data like below?
$this->session->set_userdata('userdata',$userData);
How can use the variable on view like this it is giving nothing
<?php if(!empty($userdata['given_name'])){?>
<li>HI <?php echo $userdata['given_name'];?></li>
<?php }
After reading the Codeigniter User Guide on sessions, where this is explained ( as we all have ), you could do the following...
This is demonstration code which is really good for testing stuff out like this.
The View auth_view.php for want of a better name
<h1> View </h1>
<?php if(!empty($this->session->given_name)){?>
<li>Hi <?= $this->session->given_name;?></li>
<?php }
The Controller
// $userData=$google_oauthV2->userinfo->get();
// Recreate the Array from google_oauthV2
$userData['id'] = 1;
$userData['given_name'] = 'Fred Flintstone';
$this->session->set_userdata($userData); // Save ALL the data from the array
var_dump($this->session->userdata()); // DEBUG- Lets look at what we get!
$data = $this->load->view('auth_view', NULL, true);
echo $data;
Does that help explain the possibilities?
I highly recommend reading the user guide, because I did to get this answer.
This is hard for me to answer as I don't know how the set_userdata() function works, ie will it accept an array.
But you could try:
$userData=$google_oauthV2->userinfo->get();
$this->session->set_userdata('data',$userData);
And on the view page:
<?php if(!empty($data['userData']['given_name'])){?>
<li>HI <?php echo $data['userData']['given_name'];?></li>
If that does not work this is what I would do.
$userData=$google_oauthV2->userinfo->get();
$this->session->set_userdata('userdata',$userData['id']);
$this->session->set_userdata('username',$userData['given_name']);
$_SESSION['data'] = $userData;
And on the view page:
<?php if(!empty($_SESSION['data']['userData']['given_name'])){?>
<li>HI <?php echo $_SESSION['data']['userData']['given_name'];?> </li>
<?php }
Also you are missing a right paren on:
$this->session->set_userdata('username',$userData['given_name'];
in your orginal code.
Yes, you can store data like this:
$this->session->set_userdata('userdata',$userData);
To access it from view, just store the session data into a local variable.
$userData = $_SESSION['userdata'];
then you can use it.
<?php if(!empty($userData['given_name'])){ ?>
<li>HI <?php echo $userData['given_name'];?> </li>
<?php } ?>
NOTE:
To use session in codeigniter you have to load the session library in your controllers.You can load it in constroctor or top of the method where you are going set session.(you don't have to load it to view.)
$this->load->library('session');
With help from #teresko I've managed to create dynamic pages (& their urls) for my site using the loop below. My problem is how do i get the newly created page at ahref to combine data I have in database with the template (which I already have ready), so that when the user clicks on it, she/he goes to the page populated with the data. Am i supposed to use a javascript click function (would rather not). How would i do it with php and html?
Here is the loop generating the URLs:
<?php foreach ($reciperow as $recipe) { ?>
<h2><?php echo $recipe['rectitle'];?></h2>
<p class="subhead"><?php echo $recipe['recsummary']; ?></p>
<?php } ?>
Would really appreciate a solution that stays clear of routing, since my site's a basic project and I plan to get to MVC and PHP routing in the next projects. Thanks.
If you meant How, when user clicks generated link, show him page with data from database accordingly to "id" he/she selected, then do the following:
<?php
$id = intval($_REQUEST['id']);
if ($id) { // user get here by clicking on link with id
$data = ... // fetch data from database
?>
<sometag>Some data from database:<?php echo $data['somecollumn']; ?></sometag>
...
<?php
} else {
// user just opened first page
// generate links list as usual
...
foreach ($reciperow as $recipe) {
?>
<h2><?php echo $recipe['rectitle'];?></h2>
<p class="subhead"><?php echo $recipe['recsummary']; ?></p>
<?php
}
...
}
?>
Edit:
Is this how it is normally done for simple sites?
Depends.
If you has only one entity in datadabe, then there will be no arguments clash, id is identifier only for recipies, but if you intent to show also details for, f.e. ingredients, furniture and/or more, then you must add specificators.
Like, links will look like
<a href="?show=recipie&id=<?php echo $recipe['uniqno'];?>">
<a href="?show=ingredient&id=<?php echo $ingredients['id'];?>">
... and then data must be fetched and displayed correspondingly:
$id = ...;
if ($id)
switch ($_REQUEST['show']) {
case 'recipie':
// show recipie data
break;
case 'ingredient':
// show ingredient data
break;
case ...
default:
// show start page
}
But with addition of another entities yours .php file will grow. Another solution will be to add separate scripts for handling each entity:
// generate links list as usual
...
foreach ($reciperow as $recipe) { // look at `recipie.php` portion of link's href
?>
<h2><?php echo $recipe['rectitle'];?></h2>
<p class="subhead"><?php echo $recipe['recsummary']; ?></p>
<?php
}
And add recipie.php file in the same folder as base script with following contents:
<?php
$id = intval($_REQUEST['id']);
if ($id) { // user get here by clicking on link with id
$data = ... // fetch data from database
?>
<sometag>Some data from database:<?php echo $data['somecollumn']; ?></sometag>
...
<?php
} else {
?>
<h1 class="error">No recipie ID specified</h1>
<?php
}
<?
Further exploring will bring you to concepts of MVC and routing via human-friendly-links format, when links looks like /home, /recipie/12 and/or /recipie/?id=12 or even /recipie/12-cream-pie. But that's story for another time...
Let's say I have 3 columns/divs/sections in my html layout, let's call them cat1, cat2, cat3. Then I have a database with a table called "Content". In that table I have the fields id, title, content, category.
Now I want to populate those 3 columns with their corresponding content from my mysql table. For example - get all the content from table where category = cat1(corresponding to the first column).
I could just make 3 functions that each have their own parameter, but I don't want to repeat code. How can I do this with a single function, but just using a different parameter?
I was thinking something like this:
public function displayAll_with_category ($category) {
$sql = $con->prepare("SELECT * FROM Table WHERE Category=?");
$sql->bindParam(1, $category);
$sql->execute();
while ($row = $sql->fetch()) {
echo $row['Title'];
}
}
Then in my HTML:
<div id="cat1">
// Using a central class
<?php include('class.php'); $obj = new handler; $obj->displayAll_with_category(); ?>
</div>
So far so good, I need to somehow be able to alter the $category parameter so I can use the same function to call the contents for cat1/2/3. I have no idea how to do that, usually I need to send something to the PHP function via a button or form, but this time that's not the case. Is this even doable in pure PHP? I can think of doing this with AJAX, but for now I want to know if it can be done with PHP.
I'm not sure if this is what you want.
This would get you the data for category 1, 2 and 3.
I just created a loop in the view to call the function with different parameters:
<?php
for($cont = 0; $cont<4; $cont++){
?>
<div id="cat1">
// Using a central class
<?php include('class.php'); $obj = new handler; $obj->displayAll_with_category($cont); ?>
</div>
<?php
}
?>
Oh and if I were you i would try to separate the logic from the view and I will print the result of the function in the view instead of doing it inside it.
I've built a contest system where users submit tickets then one is randomly chosen to win, and now I'm trying to figure out a way to display to users the tickets they have already submitted. Each ticket has an id, a date, and an invoicenumber. I want to display all the invoice numbers that a user has submitted so far.
Here is the method I have in my methods page. (I've organized my methods into one php file and then i just call them when needed.)
function GetSubmittedBallots()
{
if(!$this->CheckLogin())
{
$this->HandleError("Not logged in!");
return false;
}
$user_rec = array();
if(!$this->GetUserFromEmail($this->UserEmail(),$user_rec))
{
return false;
}
$qry = "SELECT invoicenumber FROM entries WHERE user_id = '".$user_rec['id_user']."'";
$result = mysql_query($qry,$this->connection);
while($row = mysql_fetch_array($result))
{
echo $row['invoicenumber'];
}
}
and then on my html page that I want it to echo on, i just call it
<?php GetSubmittedBallots(); ?>
Sadly, this doesn't work. So my question is, how would i go about displaying the $row array on my html page?
<?php
require("methods.php"); // Include the file which has the "GetSubmittedBallots" function or method, if it's in a separate file
GetSubmittedBallots(); // Run the function / method
?>
If this doesn't work, please let us know any errors you receive.
Does it echo "Array"?
That's because you are trying to echo an array.
You should use something like print_r or var_dump, given that you are just trying to access the queried results. In my opinion the method should build a multidimensional array with the records, and then the template logic should loop through them and echo the values in a nice way. Be it a table or nicely arranged HTML.
If I'm not wrong, $this keyword is indicating you're in a class? If so, you need first to init that class and try to call GetSubmittedBallots function after init;
// assuming that class's name is Users
$users = new Users();
$users->GetSubmittedBallots();
I'm trying to send from a controller to a view an array of all contacts who are in my database table "Contacts" and then display them on a drop down menu.I followed the CodeIgniter documentation about this topic http://codeigniter.com/user_guide/general/views.html but it isn't really what I would like to do.
Here is what I tried to do :
function getAll_contact(){
$exist= $this->contacts_model->get_all('contacts');
if($exist)
{
$all_contact = $this->contacts_model->read('contacts');
//echo json_encode($all_contact); prints all the contacts in the table
$this->load->view('myView', $contact);
}
}
In my view :
<select class="span4">
<?php if(isset($all_contact) && ! empty($all_contact)){
foreach($all_contact as $contact){
echo "<option value='".$contact->id_contact."'>".$contact->company."</option>";
}
}
</select>
This does not show anything on the drop down menu. Could anyone help me please ?
put ur result into data array..
$data['all_contact']=$this->contacts_model->read('contacts');
and send the array to view
$this->load->view('myView', $data);
and you can take that variable in your view with $all_contact ..like u currently have..
First of all, you've named the variable $contact instead of $all_contact.
The solution:
function getAll_contact(){
$exist= $this->contacts_model->get_all('contacts');
if($exist)
{
$data['all_contact'] = $this->contacts_model->read('contacts');
//echo json_encode($data); prints all the contacts in the table
$this->load->view('myView', $data);
}
}
Then you access it like you are currently in your view.