Basic mvc and php insert issue - php

I am trying to do a basic insert to my book table, this is the code I have so far alsong with the error I am presented with.
Model (models > adminarea_model.php)
adminarea_model.php
public function create($title_text)
{
$title_text = strip_tags($title_text);
$sql = "INSERT INTO book (title) VALUES (:title)";
$query = $this->db->prepare($sql);
$query->execute(array(':title' => $title_text));
$count = $query->rowCount();
if ($count == 1) {
return true;
} else {
$_SESSION["feedback_negative"][] = FEEDBACK_NOTE_CREATION_FAILED;
}
return false;
}
View (views > admin > addBook.php)
addBook.php
<form method="post" action="<?php echo URL;?>admin/create">
<label>Text of new note: </label><input type="text" name="title" />
<input type="submit" value='Create this note' autocomplete="off" />
</form>
Controller (controllers > admin.php)
admin.php
public function create()
{
if (isset($_POST['title']) AND !empty($_POST['title'])) {
$book_model = $this->loadModel('Admin');
$book_model->create($_POST['title']);
}
header('location: ' . URL . 'admin/addBook');
}
When I am on admin/addBook and I try to submit the form I receive the following error;
Fatal error: Call to a member function create() on a non-object in C:\xampp\htdocs\logintest\application\controllers\admin.php on line 43
Line 43 contains the following
$book_model->create($_POST['title']);
Any ideas where I am going wrong?
Quite new to php/mvc here so any advice is welcome.

This error is generated when you are trying to call a member function of a class and object is not referencing to that class, you didnot tell which mvc framework you are using but what i think this might be the fix of your error as in most of the frameworks they make object as follow:
$book_model = $this->loadModel('adminarea');
Fix the line in your controller

Related

Why does CI create a new row instead of updating?

I'm creating a UI in my application which will allow the user to decide the state of received content, this includes updating it. How does CI handle this?
I've tried the different update methods provided in the query builder part of the documentation, including replace and update, I pass on the data from the view to the controller, to the model in the form of an array. Yet still, when I try it, it creates a new row with that single value and with all other columns empty.
view.php
<form action="Application/Update" method="get">
<input type="hidden" name="mar-id" value="<?php echo $row['id']; ?>">
<input type="hidden" name="mar-read" value="New-value">
<?php echo anchor('http://localhost/dir/dir/dir/index.php/Application/Update', 'update'); ?>
</form>
controller.php
public function Update() {
$this->load->helper('url');
$this->load->model('Main');
$id = $this->input->post('mar-id');
$value = $this->input->post('mar-read');
$mar = $this->Main->Update($id, $value);
if ($mar == TRUE) {
redirect('http://localhost/dir/dir/dir/index.php/Application/Otherpage', 'refresh');
}
else {
redirect('http://localhost/dir/dir/dir/index.php/Application/Otherpage');
}
}
model.php
public function Update($id, $value) {
$data = array(
'status' => $value
);
$this->db->where('id', $id);
$update = $this->db->update('table', $data);
}
As I said, I expect the row to be updated based on the row-id provided. Instead it creates a completely new row with that single value. It doesn't return any error messages though.
There are a number of mistakes here.
SO to date we have established that performing var_dumps in the controller results in NULL for all your "POST" values.
I've assumed the following for simplicity.
Controller Name is: Program.php (Application is NOT an Allowed controller name as it's a foldername)
Model Name is: Mdl_update.php
View is: update_view.php
Issue #1:
Your Form has an issue where you are using an anchor tag which is just a link. It does nothing in submitting any data from the form.
So we have to remove the Anchor Tag and replace it with a Form Submit. You have to Submit the form to get any chance of sending the form data.
For testing your GET and POST I've added in Two different Forms.
In update_view.php
<!-- Set the Method to GET -->
<form action="program/update" method="get">
<input type="hidden" name="mar-id" value="<?php echo $row['id']; ?>">
<input type="hidden" name="mar-read" value="New-value">
<input type = "submit" name="update" value="Update with GET">
</form>
<!-- Set the Method to POST as this is what the Controller is Expecting -->
<form action="program/update" method="post">
<input type="hidden" name="mar-id" value="<?php echo $row['id']; ?>">
<input type="hidden" name="mar-read" value="New-value">
<input type = "submit" name="update" value="Update with POST">
</form>
What I used to display the Form in the controller by simply calling the program/index in the Program controller.
public function index() {
$this->load->helper('url');
$data['row'] = array('id' => 2);
$data = $this->load->view('update_view', $data, TRUE);
echo $data;
}
So your Controller is looking for POST and not GET. This can be proven by changing the controller up a bit for debugging.
public function update() {
$this->load->helper('url');
$this->load->model('mdl_update');
$id = $this->input->post('mar-id');
$value = $this->input->post('mar-read');
echo '<h2>POST Values</h2>';
var_dump($id);
var_dump($value);
// ****************************
// These are added in for debugging/Demonstration to show values for the form using the GET method.
$id_get = $this->input->get('mar-id');
$value_get = $this->input->get('mar-read');
echo '<h2>GET Values</h2>';
var_dump($id_get);
var_dump($value_get);
// ****************************
exit('Stopped for Debugging: Method '. __METHOD__.' at Line: '.__LINE__); // Added for Debug
$mar = $this->mdl_update->Update($id, $value);
if ($mar == TRUE) {
redirect(base_url('program/otherpage'), 'refresh');
} else {
redirect(base_url('program/otherpage'));
}
}
So you are looking for POST Data when your form method is set to GET. Please be aware of what you are setting. They must match.
If you want to use GET, you need to use $this->input->get()
The code above will let you test both.
So you now have a POST and GET Form and the controller is setup to demonstrate the two different types. Choose Either GET or POST!. That is up to you on which one you choose.
Issue #2: Expecting a return value from your Model when you are not returning anything.
In your Controller you have the line...
$mar = $this->mdl_update->Update($id, $value);
And in your Model you have...
public function update ($id,$value) {
$data = array(
'status' => $value
);
$this->db->where('id', $id);
$this->db->update('db_table', $data);
}
Your Model Method is not returning anything.
You should always look up what your return values are. I am expecting that your intention was to return the value of the update. Looking through the CI Code itself it appears that if things go wrong it will return FALSE (if the database debug is disabled - learnt something new)
I've added in some debug to assist in viewing what is going on here.
public function update($id, $value) {
$data = array(
'status' => $value
);
$this->db->where('id', $id);
$update_result = $this->db->update('db_table', $data);
echo $this->db->last_query(); // Added for DEBUG
return $update_result;
}
Now I cannot get your code to create new rows as you claim. It's impossible, with this code, to add new rows. So thats happening from something you haven't shown us but that is an aside and not important here.
If we alter the controller to view the model etc (I am only showing the changes ) we would change
exit('Stopped for Debugging: Method '. __METHOD__.' at Line: '.__LINE__);
$mar = $this->mdl_update->Update($id, $value);
To this
$mar = $this->mdl_update->Update($id, $value);
var_dump($mar);
exit('Stopped for Debugging: Method '. __METHOD__.' at Line: '.__LINE__);
If you run this and submit either the GET ( Results are NULL ) or POST, the update will always return TRUE. So your redirect etc needs to be looked at on how you decide on one or the other.
I think you should set your table columns to not allow them to be NULL AND add in some "Validation" in your controller.
ISSUE 3: No Form Validation
CodeIgniter has a Form Validation Class that I suggest you read. This is getting way too long to go into that here...
So as you go through this, you can add/remove debugging to test what is going on and progress it along the way as I have hopefully shown.
if anything is unclear, just ask. I'm sure I may have left something out.

Simple search on CI

This is my Controller
public function search()
{
$this->load->model('student_model')
$keyword = $this->input->post('search');
$student = $this->student_model->search($keyword);
$this->load->view('result',$student);
}
This my model
function search($keyword){
$query = $this->db->get_where('data', ['nisn' => $this->input->get('nisn')])->row();
return $query;
}
Form view
<form class="margin-bottom-small" method="POST" action="<?php echo site_url('student/search/') ?>">
<p> NISN</p>
<input type="text" name="search">
<input type="submit">
</form>
Somehow i just wanted to show
<?php echo $student->nisn;?>
<?php echo $student->name;?>
<?php echo $student->class;?>
But when i tried it always not work
it keep says syntax error, unexpected '$keyword' (T_VARIABLE)
Cant help it been trying the one on internet and it not work too
Add ; after $this->load->model('student_model')
public function search()
{
$this->load->model('student_model');
$keyword = $this->input->post('search');
$student = $this->student_model->search($keyword);
$data['student']= $student;
$this->load->view('result',$data);
}
Well, it seems you have some mistakes here are:
Semicolon (;) is required after:
$this->load->model('student_model');
You must convert this chunk into valid Array format:
array('nisn' => $this->input->get('nisn'));
Tip: When you face some of T_VARIABLE errors in PHP, it is recommended to check the lines before the line shown in the error itself.
For your knowledge: Please have a look at
List of Parser Tokens !
I think this little change in your modelfuntion will fix the problem
function search($keyword){
$query = $this->db->get_where('tablename', ['field' => $keyword])->row();
return $query;
}
so in your case,code will be like this
function search($keyword){
$query = $this->db->get_where('data', ['nisn' => $keyword])->row();
return $query;
}

How to call class method as form action php mvc application if it's even possible?

I'm trying to write a simple mvc application with php and mysql. I'm very new to mvc and relativly new to php aswell. I'm letting the user choose from different movies and then add the ones they want to their own list. But I can't figure out how to get the correct form action to insert the choosen movie into the db.
This is how my two model class methods looks like:
public function checkMovie() {
// Check if movie exist in db.
$stmt = $this->dbh->prepare("SELECT * FROM watchlist WHERE my_title='{$_POST['my_title']}'");
$stmt->bindParam(':my_title', $_POST['my_title']);
$stmt->execute();
$rows = $stmt->fetchALL();
$this->n = count($rows);
}
public function addMovie() {
// Add choosen movie to db.
$sql = $this->dbh->prepare("INSERT INTO watchlist(my_title, my_des, my_link)
VALUES ('{$_POST['my_title']}', '{$_POST['my_des']}', '{$_POST['my_link']}')");
$sql->bindParam(':my_title', $_POST['my_title'], PDO::PARAM_STR);
$sql->bindParam(':my_des', $_POST['my_des'], PDO::PARAM_STR);
$sql->bindParam(':my_link', $_POST['my_link'], PDO::PARAM_STR);
$sql->execute(array(':my_title' => $_POST['my_title'],':my_des' => $_POST['my_des'],':my_link' => $_POST['my_link']));
}
As you can see I have the basic sql-code in here and then I call the methods from a method in my controller:
public function getAddMovie() {
$this->addModel = new AddMovieModel();
if (isset($_POST['submit'])) {
// Call checkmovie from addmoviemodel and check if movie allready is taken.
$checkmovie = $this->addModel->checkMovie();
if($this->n > 0) { // Should this logic perhaps be in my model?
// Shows javascript-popup eg. 'movie allready added'.
include 'view/viewscripterror.php';
}
else { // Call addMovie from addmoviemodel to insert movie to db.
$addmovie = $this->addModel->addMovie();
// Shows javascript-popup eg. 'movie is now added'.
include 'view/viewscriptsuccess.php';
}
}
}
I'm not sure if the if($this->n > 0) perhaps should be in my model aswell?
And here's the form, I can't figure out what to pass as form action? This problem has been driving me crazy for a while now and that's why I'm turning here in hope for some help.
echo '<form action="??" method="post">',
'<input type="hidden" name="my_title" value="'.$title.'">',
'<input type="hidden" name="my_des" value="'.$description.'">',
'<input type="hidden" name="my_link" value="'.$link.'">',
'<input type="submit" name="submit" value="Peppa!">',
'</form></div>';
Try like
echo '<form action="http://site_url/getAddMovie" method="post">',
You need to pass the url of the function getAddMovie into the action,then after submitting it,it will post/get the params into that function.
And try to load the model like
$this->load->model('AddMovieModel');
And try to call it like
$checkmovie = $this->AddMovieModel->checkMovie();
Or even you can try like
$addModel = new AddMovieModel();
and call it like
$checkmovie = $addModel->checkMovie();

my update query didn't work on Codeigniter

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.

CodeIgniter search form

I am currently learning CodeIgniter and I am looking to develop a simple example consisting of 2 forms, let’s call them form a and form b. Form a has one edit field called “LastName” and form b will displays a list of all names in a table matching the value in “LastName” something like
select first_name, last_name from my_table where last_name = :LastName
I need this example to understand the mechanisms of passing variables from one form and controller to another. I am guessing this is using a method like $_POST but no examples on the web look very clear.
So you would have a form...
<form action="/controller/name/" method="post">
<p>Last Name: <input type="text" name="LastName" /></p>
<p><input type="submit" value="Submit"/></p>
</form>
Then in your controller (assuming your already connected to the database):
function index() {
// This is the last name from the form
$LastName = $this->input->post('LastName');
// Create the query
$sql = "SELECT * FROM users WHERE last_name = ?";
// Execute it, replacing the ? with the last name from the form
$query = $this->db->query($sql, array($LastName));
// Show results
foreach ($query->result() as $row) {
echo $row->first_name . "<br />";
echo $row->last_name;
}
}
Your view folder: application/view/form_a.php, application/view/forma_b.php
Your controller folder: application/controller/controller_name.php
Your model folder: application/model/related_model_name.php
Your controller_name.php file:
class Controller_name extends Controller
{
function index()
{
$this->load->view('form_a'); //this loads the form
}
function results()
{
$name= $this->post->input('last_name');
$this->load->model('related_model_name'); //this is the model to fetch the data
$data['names']= $this->related_model_name->searchByLastName($name);
if(!empty($data))
$this->load->view('form_b', $data);
}
}//eoc
Your related_model_name.php file
class Related_model_name extends Model
{
function __construct()
{
parent::Model();
}
function searchByLastName($name)
{
$query = $this->db->get_where('table_name', array('last_name'=>$name));
if($query->nu_rows() > 0)
return $query->results();
}//eof
}//eoc
Your form_b.php view file
do a print_r($data) and that should give you an idea of how to display the data.
it maybe something like
foreach ($names as $name)
{
echo $name->name;
}
I realize this thread is old, but I am new to CodeIgniter and have been working with a similar challenge. My challenge is to create a search form that finds growers in a specific zip code. Here is my solution. It's simpler than I expected and might help someone else.
This code assumes you are connected to your database and have a standard MVC CI application, etc.
I handle most of this task in the model and view, but I do have this method in my controller:
public function result()
{
$zipcode = $this->input->post('zip_code');
$query = $this->db->get_where('growers', array('zip LIKE' => $zipcode));
return $query->result_array();
}
In my model, I used the following method:
public function result()
{
$zipcode = $this->input->post('zip_code');
$query = $this->db->get_where('growers', array('zip LIKE' => $zipcode));
return $query->result_array();
}
I have three views -- one page (located in views/pages/search.php), and two widgets --one for the search form and one for the search results (located in views/widgets/result).
I have the search result form on the same page that the results display. However, each section is contained in its own view file, which I have placed in views/widgets. The code for this section in the page view is:
<div class="search" style="margin-top:0px;">
<?php
$this->load->view('widgets/search');
?>
</div>
</div>
<div id="results">
<div id="grower-info">
<?php
$this->load->view('widgets/result');
?>
</div>
</div>
The search form widget is:
<form action="search-results" method="post">
<input type="text" maxlength="10" name="zip_code" value="zip code" size="10">
<input type="submit" name="submit" value="SEARCH">
</form>
The search result widget is:
<?php
$results = $this->pages_model->result();
foreach ($results as $result)
{
echo '<h4>'.$result['company'].'</h4>';
echo $result['address_1'] . ' ' . $result['address_2'].'<br>';
echo $result['city'].', ' . $result['state'] . ' ' . $result['zip'].'<br>';
echo 'Phone: ' . $result['office_phone'].'<br>';
echo 'Fax: ' . $result['office_fax'].'<br>';
echo 'Website: ' . $result['website'].'<br>';
echo '<br>';
echo '<hr>';
}
if (count($results) < 1) {
echo 'No results found. Please try your search again, or try another search.';
}
?>
I hope that helps someone!

Categories