Simple search on CI - php

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;
}

Related

Kill the execution of controller after $this->load->view, Codeigniter

Hi I am using codeigniter for site and i am calling a function in a controller through a form in my php page the function call is:
Gear.php:
foreach ($gearArray as $key => $value) {
echo '<tr><td><img id="leftimg" src="'.base_url().''.$value["Product_Image_URL"].'"></td>';
echo '<td>'.$value["Description"].'';
echo '<form method="post" id="addtocart" action="'.site_url('GearController/addorUpdate').'">';
echo '<input type="hidden" name="desc1" value="'.$value["Name"].'">';
echo '<input type="hidden" name="cost1" value="'.$value["Price"].'">';
echo '<input type="submit" value="Add To Cart">';
echo '</form></td>';
}
echo '</table>';
?>
From this the method inside the GearController is called through
action="'.site_url('GearController/addorUpdate').'"
inside the function which is an add to cart function, i am checking whether the item is already in the cart or not and then updating it,once updated i am trying to redirect to a page using:
GearController.php:
public function addorUpdate(){
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->model('CartModel','cart');
$boolean = FALSE;
$Description = $this->input->post('desc1');
$data['cartArray'] = $this->cart->return_cart();
foreach ($data['cartArray'] as $value) {
if($Description==$value['Description']){
$boolean = TRUE;
}
}
if($boolean==TRUE){
$this->updateCart($Description);
}
}
public function updateCart($Description){
$updatearray = array(
'Quantity'=>'Quantity+1',
'Price' => 'Price * Quantity',
);
$this->load->model('CartModel','cart');
$update_order = $this->cart->update_cart($updatearray,$Description);
$data['cartArray'] = $this->cart->return_cart();
$this->load->helper('url');
$this->load->view('cart',$data);
}
The problem here is that everything works fine, the page gets redirected but within seconds it displays a blank screen. I tried return, die and exit. None of it helps. It seems like the controller is executing the code under the $this->load->view. I am telling this because i previously had a function under the
if($boolean==TRUE){
$this->updateCart($Description);
}
That particular code was executed after the redirect. Could someone please help?
This sound like you might have what is call a BOM character at the start of your view file. This character is usually invisible. Make sure that there are not (apparently) black characters at the beginning.
You can also test that updateCart($Description) is running by temporarily putting this code as the first line of the function echo "This is updateCart; Then comment out all the other code in that function. If you see that text on the screen you know the function runs.
This doesn't answer your question but it's bugging me so...
Instead of this mess
foreach ($data['cartArray'] as $value) {
if($Description==$value['Description']){
$boolean = TRUE;
}
}
if($boolean==TRUE){
$this->updateCart($Description);
}
You could simply do this
if(in_array( $Description, array_column($data['cartArray'],'Description'))){
$this->updateCart($Description);
}
You can test it with this code (mockup)
$Description = 'foo';
$data = ['cartArray' => [
['Description' => 'foo'],
['Description' => 'bar'],
]
];
if(in_array( $Description, array_column($data['cartArray'],'Description'))){
echo "found";
}
Outputs
found
Test it here
https://3v4l.org/W5oB5
I think in_array is pretty self evident but here is array_column which is highly useful and often overlooked.

Strange table update codeigniter $this->db->update

I'm having a problem with an update of one table in the db. I always use the same approach and I have no problem. Although in this case I have an issue...
The code:
the view:
<fieldset>
<legend>Modifica Dati Check-in Cliente</legend>
<?php
$passeggeri='placeholder="Passeggeri"';
$animali='placeholder="Animali"';
$note='placeholder="Note"';
echo form_open('site/esegui_modifica_record_check_in');
echo form_hidden('id',$id[0]->id);
echo form_hidden('rif_parcheggio',$id[0]->rif_parcheggio);
echo form_input('Passeggeri',set_value('passeggeri',$id[0]->passeggeri),$passeggeri);
echo form_input('Animali',set_value('animali',$id[0]->animali),$animali);
echo form_input('Note',set_value('note',$id[0]->note),$note);
?> <br/> <input type="datetime-local" name="data_in_inserita" value="<?php echo strftime('%Y-%m-%dT%H:%M', strtotime($id[0]->data_in));?>" /> <?php
echo form_submit('submit','Modifica');
echo form_close();
?>
</fieldset>
controller:
function esegui_modifica_record_check_in() {
$this->load->model('membership_model');
if($query = $this->membership_model->esegui_modifica_record_check_in())
{
$this->load->view('check_in_auto_succesful');
}
else
{
$this->load->view('admin');
}
}
model:
function esegui_modifica_record_check_in() {
$update_record_check2= array (
'passeggeri' => $this->input->post('passeggeri'),
'animali' => $this->input->post('animali'),
'note' => $this->input->post('note'),
'data_in' => $this->input->post('data_in_inserita')
);
$id=$this->input->post('id');
$this->db->where('id',$id);
$insert = $this->db->update('check2', $update_record_check2);
return $insert;
}
The query is executed but the values are updates as zero (0) character for the modified fields.
It's very strange! this is my first problem with the update function of codeigniter
I don't have a clear idea. Could you please help me?
thanks a lot
by
First thing to debug is to make sure that values are really being passed into your model method. Either debug first on the controller or inside you model:
Controller:
function esegui_modifica_record_check_in()
{
var_dump($this->input->post());
// rest of codes
}
OR
Model:
function esegui_modifica_record_check_in()
{
var_dump($this->input->post());
// rest of codes
}
Then, assuming you haven't fixed it yet. You have a case mismatch on the input name=""
echo form_input('Passeggeri',set_value('passeggeri',$id[0]->passeggeri),$passeggeri);
'passeggeri' => $this->input->post('passeggeri'),
// Passeggeri !== passeggeri
echo form_input('Animali',set_value('animali',$id[0]->animali),$animali);
'animali' => $this->input->post('animali'),
// Animali !== animali
echo form_input('Note',set_value('note',$id[0]->note),$note);
'note' => $this->input->post('note'),
// Animali !== animali
You should take that also into account. You need to follow the same case letters. Make them the same
Either:
echo form_input('Passeggeri',
$this->input->post('Passeggeri')
Or
echo form_input('passeggeri',
$this->input->post('passeggeri')
Sidenote:
As my suggestion above, I would just make it simple and use a normal form.
<form method="POST" action="<?php echo site_url('site/esegui_modifica_record_check_in'); ?>">
<input type="text" name="passeggeri" value="<?php echo $id[0]->passeggeri; ?>" placeholder="Passeggeri" />
<!-- and other text box inputs -->
</form>

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>

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