CodeIgniter search form - php

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!

Related

Basic mvc and php insert issue

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

Learning OOP in PHP. Is this the correct way to do this?

I've just started learning to do oop and I just wanted to put the most basic set of code together to make sure I'm understanding things correctly. I wanted to capture a form entry in the $_POST variable and pass it to an object to have it output something back to the browser. No SQL, no Security measures, just proof of understanding.
Here is the form:
<html>
<head>
<title>SignUp Form</title>
</head>
<body>
<?php
if(!empty($_POST['name'])) {
include_once "class.php";
} else {
?>
<form method="post" action="signup.php">
<label for="name">Enter name below:</label></br>
<input type="text" name="name" id="name"></br>
<input type="submit" value="Submit">
</form>
<?php
}
echo $name->processName($_POST['name']); ?>
</body>
</html>
And here is the class:
<?php
class Process {
public $entry;
function __construct($entry) {
$this->entry = $entry;
}
public function processName($entry) {
return "You entered " . $this->entry . ".";
}
}
$name = new Process($_POST['name']); ?>
This is working without error right now but it doesn't seem like I should have to enter the $_POST in the echo statement on the form page and in the object on the class page. Is this correct? Should I instead be collecting that in the $entry property. It's working, but I don't think the execution is correct. Thanks in advance!
Your right you don't need to enter the $_POST variable into that function, you could change it to this and it would work without entering the post:
public function processName() {
return "You entered " . $this->entry . ".";
}
Because right now processName function doesn't do anything with the class's public $entry variable, it just echoes out what you put in when you call the function.
What you likely want to do instead is:
Change public $entry; to protected $entry;
Then:
public function getEntry() {
return $this->entry;
}
Then in your html, after constructing the class, you can just put this to get the $entry variable:
echo $name->getEntry();
Coming from Symfony framework background. You could do something right this:
<?php
class Process
{
protected $post_var;
public function __construct($p)
{
$this->post_var = $p;
}
public function getData()
{
//checking if not post request
if(count($this->post_var) == 0) {
return false;
}
$result_arr = [];
//populating $result_arr with $_POST variables
foreach ($this->post_var as $key => $value) {
$result_arr[$key] = $value;
}
return $result_arr;
}
}
$process = new Process($_POST);
$data = $process->getdata();
if($data)
{
echo $data["name"];
}
?>
<form action="" method="post">
<input type="text" name="name"/>
<input type="submit" name="submit"/>
</form>

How to display form fields even if the iterated array is empty?

Question Updated:
I am using codeigniter, The problem that i'm having is that, if the array contains values then the form elements will show. if the array is empty the entire form will not show. so imagine this as a edit form where a person has selected to edit a record. and lets say for whatever reason the record that is being edited has no records, its completly empty. and lets also say the id must be visible and be editable regardless of it being empty or not. so what happens is if the record is empty the entire form elements will not show. so what i'm trying to do is have it display regardless if there are records or not.
<?php
//controler
public function show()
{
$this->load->model('my_model');
$data = array(
'data' => $this->my_model->getdata();
);
$this->load->view('somepage', $data);
}
//model
public function my_model()
{
$q = $this->db->get_where('some query', array('id' => $id));
if($q->num_rows() == 1)
{
foreach($q->result() as $row)
{
$rows[] = $row;
}
return $rows;
}
else
{
return array();
}
}
//view
//note: this will only work if the array has data, otherwise everything between the foreach statement wont show.
<?php foreach($data as $row) : ?>
<input type="text" name="something" value="<?=$row->column1;?>">
<input type="text" name="something" value="<?=$row->column2;?>">
<input type="text" name="something" value="<?=$row->column3;?>">
<input type="text" name="something" value="<?=$row->column4;?>">
<input type="text" name="something" value="<?=$row->column5;?>">
<?php endforeach; ?>
in your view
<?php
if (!empty($data)) {
var_dump($data);
} else {
//print out nothing
}
?>
or you can do following
<p><?= (!empty($data)) ? $data : "" ?></p>

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.

Categories