Codes:
View
<html>
<body>
<?php echo form_open('samplecontroller/sample'); ?>
<input type="text" name="samplename"/>
<input type="submit" value="go"/>
<?php echo form_close(); ?>
</body>
</html>
Controller
<?php
Class samplecontroller extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('Sample_insert');
}
function index()
{
$this->load->view('sample.php');
}
function show($data)
{
$this->load->view('sampleresult',$data);
}
function sample()
{
if($result = $this->Sample_insert->insert_into_sample())
{
$this->show($result);
}
}
}
?>
Model
<?php
Class Sample_insert extends CI_Model
{
function insert_into_sample()
{
$sample = array(
'samplename' => $this->input->post('samplename'),
);
$this->db->insert('sample', $sample);
$latest_id = $this->db->insert_id();
return $latest_id;
}
}
?>
The flow is that, i have 2 views. The other one contains only 1 text input, after which goes to controller then controller passes it on to model then model gets the value within the text input then inserts to my sample table.
The sample table has 2 columns, id(PK,AI) and name
after it inserts, on my model. i added a line, return $latest_id. Then passes goes back to my controller then passes it off to another view that only has
print_r($data);
After all that, it displays an error.
Message: Undefined variable: data
Im not sure where the flow went wrong or if i made a syntax mistake. If someone knows/expert on insert_id(), could you pin point where exactly i am wrong? anyways, ive made my research and been getting results on the web how buggy insert_id is. Im not sure if its true or not but ive been redirected mostly to forums wherein insert_id returns null and some say its a bug. Im hoping it isnt.
As per your comment, You have to do some changes in your controller.
function show($data)
{
$this->load->view('sampleresult',array("data"=>$data));
}
You can get inserted id in view in the name of $data.
For ex:
echo $data;
Edit: As per your comment in answer, For multiple row insert in model, add below code
$id_arr = array();
foreach($sample_data as $sample)
{
$this->db->insert('sample', $sample);
$id_arr[] = $this->db->insert_id();
}
return $id_arr;
Now in your view, you will get ids in $data
foreach($data as $id)
{
echo $id;
}
Related
I want to create a dynaic page, I have created model and controller and also data subitted in database successfully. Now, i'm having problem while displaying that data on front end.
Here is my Modal:
function getcorporate(){
$q="SELECT * from corporate";
$query=$this->db->query($q);
return $query->result_array();
}
Here is my Controller:
function corporate()
{
$popular['popular'] = $this->auth_model->getPopularcourses();
$data1['corporate'] = $this->auth_model->getcorporate();
$data["institute_details"] = $this->auth_model->getInstitutedetails();
$data1['course'] = $this->auth_model->getcoursesdetailes();
$this->load->view('nulearnFront/header', $data);
$this->load->view('nulearnFront/corporate', $data1);
$this->load->view('nulearnFront/footer', $popular);
}
Try this
First you can print_r() the data you receive.
print_r($corporate);
After that you can use foreach to display all the data
foreach($corporate as $value)
{
////do code according to your requirement
}
I hope this may be help out to solve your problem
Add View file this code
<?php
if (isset($corporate) && !empty($corporate)) {
foreach ($corporate as $cdata) {
echo $cdata->YourValue(db column name);
}
}
?>
You are so close to the answer. You are passing the data from your Controller class. So what you have to do is just get that data as the follows,
I get the corporate values as it is returning an array data. So here you go,
In your view.php file,
<?php
if (isset($corporate)) { // Check if the data is set or not
foreach ($corporate as $corporateData) {
?>
// Your HTML goes here, table or etc.
<?php echo $corporateData->databaseColumnName // Value that need to print from the database ?>
<?php
}
}
?>
Hope this helps you.
print the query and run it to check
function getcorporate(){
$q="SELECT * from corporate";
$query=$this->db->query($q);
print_r($this->db->last_query());die();
return $query->result_array();
}
if query works fine then you can foreah the query
foreach($corporate as $corporate)
{
echo corporate;
}
if it does not return result then change result_array() to result() in model
New to PHP and CodeIgniter framework.
I have a single question in the database and i can save the answer properly. But i'm struggling to save the answer to the allocated user_id and output the score to the user in the end of the test.
If answer is correct, it will show 1/1 else 0/1. Can someone please assist me?
** From table user_login only id is needed, table results is this and table exercises is that.
This is my Controller:
class Home extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('Exercise');
}
function exercise_demo() {
//get the exercise out of the database to give to
//the view so that it can be shown.
$this->load->model('Exercise');
//give this to the view in an array
$data = array();
$data['exercise'] = $this->Exercise->load_exercise('Geography', '2');
$this->load->view('exercise_demo', $data);
}
function storedemo() {
$answer = $this->input->post('answer');
$id = $this->input->post('exerciseid');
$this->load->model('Exercise');
$correct = $this->Exercise->check_answer($id, $answer);
//store this in a database table
$data = array(
'answer_given' => $this->input->post('answer'),
'exercise_id' => $this->input->post('exerciseid'),
'result_tf' => $correct,
'user_id' => '0'
);
//transfer data to model
$this->Exercise->insert_result($data);
} }
This is my Model:
class Exercise extends CI_Model {
function __construct() {
parent::__construct();
}
public function load_exercise($topic, $difficulty) {
return $this->db->get_where('exercises', array('topic' => $topic, 'difficulty' => $difficulty))->row();
}
function insert_result($data) {
$this->db->insert('results', $data);
$is_inserted = $this->db->affected_rows() > 0;
if ($is_inserted) {
echo 'Answer saved!';
} else {
echo 'Something went wrong. No insert ):';
}
}
public function check_answer($id, $answer) {
//get the exercise out of the db
$exercise = $this->db->get_where('exercises', array('id' => $id))->row();
return $exercise->solution == $answer ? '1' : '0';
}
}
This is my View exercise_demo:
<div>
<form method="post" action="<?= base_url('index.php/home/storedemo') ?>" >
<div id ="exercise">
<?= $exercise->exercise ?>
</div>
<input type ="hidden" name ="exerciseid" value="<?= $exercise->id ?>">
<input type="submit">
<br />
<br />
<h3> SCORE: </h3>
<div id="result">
<h3><?= $result ?> / 1 </h3> (comment this out to work properly)
</div>
</form>
</div>
</html>
Let's work from start to end.
function storedemo gets the posted answer
It sends it to check_answer to find if it's correct or not.
check_answer returns the string 'correct' if true and 'incorrect' if false.
storedemo then uses insert_result to place the return of check_answer into the database column result_tf
result_tf is a tiny int. You're trying to pass a string into an int column. This is most definitely not going to work.
Have check_answer return the ints 1 or 0 instead of the strings 'correct' or 'incorrect' and that will allow you to insert that into result_tf
If your code still isn't giving expected results, it's because there are other problems. If so, debug it yourself a little longer now that you're a little closer, if you're still absolutely lost after a while, I'd recommend you post a new question.
I am writing a program that basically does stuff with a database, I am having trouble with some of the functionality though, this is what it is supposed to do
public function clist() {
$this->load->model('list_model');
$fields = $this->list_model->listcli();
if ($fields === $this->list_model->listcli()) {
$fieldl = $fields;
$this->load->view('clientlist');
$this->clientlist->display_clients($fieldl);
}
}
This loads the model which looks like this:
public function listcli()
{
$this->db->list_fields('clients');
}
}
Then runs the model function listcli so that it will list all the fields in the clients database and puts the value into $fields I then call it fieldl and load a view that will show the data, the view looks like this:
<html>
<body>
<p> sup </p>
<?php
function display_clients($fieldl)
{
?>
<html>
<body>
<p> sup2 </p>
<ul>
<?php
foreach ($fieldl as $l) {
?>
<li>
<?php echo $l;?>
</li>
<?php
}
}
Then calls the function inside the view and passed the data from $fieldl into it.
but I am getting the error " Call to a member function display_clients() on a non-object in /codeigniter/src/application/controllers/clientlist.php on line 40"
line 40 is
$this->clientlist->display_clients($fieldl);
Can you help? Please and thank you.
(I know this kind of question has been asked before but they are always very specific to the code at hand so doesn't help me, I am really new to CodeIgniter so if you can keep any answer relatively simple I will be grateful).
I needed to use the second parameter possible to pass my data over into the view, not my own makeshift solution for it, CI accepts an object as a second parameter for the CI_Loader::view()
Why can't you prepare the list in the controller and pass it to view via $data array?
$my_list = '<ul>';
foreach ($fieldl as $l) {
$my_list .= '<li>'.$l.'</li>';
}
$my_list .= '</ul>';
$data['my_list'] = $my_list;
then you can access it in view as $my_list. Just echo it where you need it.
EDIT:
AS per your own answer, yes - exactly. Using example above you would pass the $data to view as the second parameter:
$this->load->view('my_view',$data);
Then in the View, you access $data['my_list'] as $my_list, $data['foo'] as $foo etc.
I want to display individual values passed from controller to view page but when i try to do so iam getting error has TRYING TO GET PROPERTY OF NON OBJECT so request ci developers to help me
This is my controller page
$data['showdata'] = $this->searchresultss->login($per_page,$look,$age, $age_to,$age_from,$se_ct,$subsect,$coun_try,$sta_te, $ci_ty,$qualification);
$this->load->view('searchresult',$data);
**This is my view page**
<?php
echo "<pre>";
print_r($showdata);
if (isset($showdata)){
foreach ($showdata as $key) {
?>
<?php echo($key->gender); ?>// This is the line where iam getting error
<?php
}
}
?>
**Here is my model page**
<?php
Class Searchresultss extends CI_Model
{
function login($per_page=3,$look,$age,$age_to,$age_from,$se_ct,$subsect,$coun_try, $sta_te, $ci_ty,$qualification)
{
$query="SELECT *
FROM users
";
$data=array();
$query=$this->db->query($query);
$data['results']=$query->result_array();
$data['count']=$query->num_rows();
$data['pages']=ceil($data['count']/3);
return $data;
}
}
I am geting error has trying to get property of non object. I am trying to print individual values passed from controller to view page ..but I am not able to do so.
You are not load the model in controler. Load the model searchresultss in controller before calling the model function. Like,
$this->load->model('searchresultss');
And
Change
echo($key->gender);
To
echo $key['gender'];
This will solve the issue
your echo is not wrong.
but i guess you didnt take the result of your query so:
try this :
if (isset($showdata)){
foreach ($showdata->result() as $key){ // just add ->result() after $showdata
echo($key->gender); ?>
}
}
I have a table name "Category" which contains (cat_id, name, description). I can insert, retrieve, and delete without any problems. But when I update my Category, no data inserted in my database. I check my table and the result is nothing.
The POST model "Category_Model extends CI_Model":
public function custom_query($data)
{
$q = $this->db->query($data);
return $q;
}
The POST controller "Category extends CI_Controller":
public function edit_category()
{
$data['title'] = "Edit Category Page";
$this->load->view('edit_category', $data);
}
public function update_category()
{
$id = $this->input->post('cat_id'); // I try $id = $this->uri->segment(3); but no result
$name = $this->input->post('name');
$desc = $this->input->post('description');
$this->post_model->custom_query("update category set cat_name='".$name."', description='".$desc."' where cat_id='".$id."'"); // when I delete 'where cat_id='".$id."'' clause, all my records were changing/updating
// I change to $this->db->where('cat_id', $id); $this->db->update('category'), but no result.
redirect ('category/view_categories');
}
Here is my EDIT CATEGORY view:
<form action="<?php echo base_url(); ?>category/update_category" method="POST">
<fieldset>
<legend>Edit Category</legend>
<label for="cat">Name :</label>
<input type="text" name="name"/>
<label for="desc">Descriptions :</label>
<textarea name="description" cols="40" rows="2"></textarea>
<input type="submit" value="Update">
</fieldset>
</form>
Please anyone tell me what was wrong with my code? Thank in advance
best regards.
*note: I put 'database' in autoload config.
First of all, are you sure you writing table name correctly?
..."update kategori..."
If this is ok, try to output your query before sending it to database, like this:
$query = "update kategori set cat_name='".$name."', description='".$desc."' where cat_id='".$id."'";
error_log('My query: ' . print_r($query, true));
$this->post_model->custom_query($query);
Then, if you won't see any problems in that query, give it to us.
It looks like your query might not be getting the cat_id as I don't see it anywhere in the passing view. Try a hidden field in the HTML which contains the cat_id. This might also be easier than trying to get it via URI segments.
You could be learn about CI models, it will simplify your life.
I believe with, for some reason, the redirect could be close your connection before the commit... It doesn't occur if you use the model object.
A little sample for models...
Create a class on application/models, like this
file "category_model.php"... attention for this name, because the CI is very restrictive with model name. Must by equal class name, but all lowercase.
class Category_model extends CI_Model {
// your fields
var $id = null;
var $name = null;
// call parent constructor... it's essential
function __construct() {
parent::__construct();
}
// create a set function, for fill all fields directly from get or post
function set($data) {
$this->id = isset($data['id']) ? $data['id'] : null;
$this->name = isset($data['name']) ? $data['name'] : null;
}
// execute update on database
function update($id) {
$this->db->update('category', $this, array('id' => $this->id));
}
}
on the controller, instance and invoke the model
$this->load->model('Category_Model', null, true);
$this->Category_Model->set($this->post());
$this->Category_Model->update();
after this, proceed you normal code.