I'm trying to build a small blog with CodeIgniter, and for some reason I put form database entries 0 instead of strings. I tried to put it through the controller manually and it works. What's the problem in a form?
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class site_model extends CI_Model {
var $title = '';
var $content = '';
var $date = '';
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function get_records()
{
$query = $this->db->get('posts');
return $query->result();
}
function add_records($data) {
$this->db->insert('posts', $data);
return;
}
function updata_records($data) {
$this->db->where('postID', $id);
$this->db->updata('posts', $data);
}
function delede_roe() {
$this->db->where('postID', $this->uri->segment(3));
$this->db->delete('posts');
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
the form page:
<div class="grid_11">
<h2>About</h2>
<?php echo form_open('site/creata'); ?>
<label for="title"> title </label>
<input type="text" name="title" id="title">
<label for="content"> content </label>
<input type="text" name="content" id="content">
<br>
<input type="submit" value="send">
<?php echo form_close(); ?>
</div>
the controler:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class site extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* #see http://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$this->load->view('home');
}
function add_post() {
$this->load->view('add_post');
}
function creata() {
$data = array (
'title' => $this->input->post('title'),
'post' => $this->input->post('content')
);
$this->load->model('site_model');
$this->site_model->add_records($data);
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
Your controller function should look something like this:
function creata() {
if( $this->input->post(null) ){ //enter if the form is submitted
$data = $this->input->post(null, true); // get all the data of the post
print_r( $data );die; // see the post data
$this->load->model('site_model');
$this->site_model->add_records($data);
$this->session->set_flashdata('msg', 'A msg to show to the user about the insertion');
redirect('site/creata', 'refresh');
}else{ //load the form
$this->load->view('home');
}
}
You form looks okay to me tho. You model may contain one extra line to view the query.
function add_records($data) {
$this->db->insert('posts', $data);
$this->db->last_query(); die; //check the query it's executing.
return;
}
Related
I want to store a checkbox array value by using implode function.when i stored,the database table value as Array (not a integer value show only array)
This is my view file:
<div class="col-sm-12">
<div>
<label class="form-control-label">Select Asset Type</label><br>
<div class="border-checkbox-section">
<div class="border-checkbox-group border-checkbox-group-primary">
<?php $b=0; foreach($assettype as $assettype_info){ $b++;?>
<input type="checkbox" name="assettype_name[]" class="border-checkbox" value="<?php echo $assettype_info->assettype_name; ?>" id="checkbox<?php echo $b;?>">
<label class="border-checkbox-label" for="checkbox<?php echo $b;?>"><?php echo $assettype_info->assettype_name; ?></label>
<?php } ?>
</div>
</div>
</div>
My Controller:
public function insertassetassign()
{
$employee=$_POST['employee'];
$assettype_name = implode(", ", $_POST['assettype_name']) ;
$assign_date = date("Y-m-d",strtotime($_POST['assign_date']));
$_POST['assetassign_status']='1';
$joinon=date('Y-m-d');
$result = $this->insert->insertrecord('assetassign');
if($result)
{
redirect('assets/assetassignment', 'refresh');
}
}
My Model :
Public function insertrecord($Table)
{
$Inputs=$_POST;
$Inputs["joinon"]=date("Y-m-d");
$Keys=array();
$Values=array();
foreach($Inputs as $Inp_key=>$inp_value)
{
if($Inp_key!="submit" && $Inp_key!="PHPSESSID")
{
$Keys[]= $Inp_key;
$Values[]= "'".$inp_value."'";
}
}
$keys=implode(',',$Keys);
$values=implode(',',$Values);
$qry="insert into ".$Table."(".$keys.") values(".$values.")";
$ack=$this->db->query($qry);
if($ack) return true; else return false;
}
I expected to store a array value as id with comma
DB shows as :
Db shows as
modified in controller to get the answer.
public function insertassetassign()
{
$employee=$_POST['employee'];
$assettype_name = implode(",",$_POST['assettype_name']) ;
$_POST['assettype_name'] = $assettype_name;
$assign_date = date("Y-m-d",strtotime($_POST['assign_date']));
$_POST['assetassign_status']='1';
$joinon=date('Y-m-d');
$result = $this->insert->insertrecord('assetassign');
if($result)
{
redirect('assets/assetassignment', 'refresh');
}
}
This is the code
My Controller file
public function view_resume($id)
{
$this->load->model('ORB_Model');
$data['get_masterData'] = $this->ORB_Model->get_masterData($id);
}
My Model file:
public function get_educationData($id)
{
return $this->db->get_where('edu_tb',['edu_id'=>$id],2)->result_array();
}
My View File:
<?php
print_r($get_educationData);
die;
// output array()
foreach ($get_educationData as $key){
?>
value="<?php echo $key->['edu_name']; ?>"
<?php
}
?>
Now when i print_r my $get_educationData it will give empty array() only.
my data is not coming from model.
in my view file nothing shown there.
Your controller should be like this :
You have to call get_educationData method also in your controller like this :
public function view_resume($id)
{
$this->load->model('ORB_Model');
$data['get_masterData'] = $this->ORB_Model->get_masterData($id);
$data['get_educationData'] = $this->ORB_Model->get_educationData($id);
/* load view here like this */
$this->load->view('your_view' ,$data);
}
Your model get_educationData should be like this :
public function get_educationData($id)
{
if ( ! empty($id))
{
$query = $this->db->get_where('edu_tb', array('edu_id' => $id));
}
else
{
$query = $this->db->get('edu_tb');
}
if ($query->num_rows() > 0)
{
return $query->result_array();
}
}
Your view should be like this :
Instead of object notation use array since your return data is in array form
<?php
//print_r($get_masterData);
//print_r($get_educationData);
if ( ! empty($get_educationData))
{
foreach ($get_educationData as $item)
{
echo $item['edu_name'];
}
}
?>
I have a problem with my shopping cart system using cakephp + bootstrap modal. The problem is that when I click/select one of my images, it will add to the cart but it will always display the last item/data in my database. Even though I'v selected the first item, it will still display the last item/data in my database. Please help me out of this.
CartsController.php
class CartsController extends AppController {
public $uses = array('Sidedish','Cart');
public function add() {
$this->autoRender = false;
if ($this->request->is('post')) {
$this->Cart->addProduct($this->request->data['Cart']['product_id']);
}
echo $this->Cart->getCount();
}
public function view() {
$carts = $this->Cart->readProduct();
$side_dishes = array();
if (null!=$carts) {
foreach ($carts as $productId => $count) {
$side_dish = $this->Sidedish->read(null,$productId);
$side_dish['Sidedish']['count'] = $count;
$side_dishes[]=$side_dish;
}
}
$this->set(compact('side_dishes'));
print_r($carts);
print_r($side_dishes);
}}
views/Orders.ctp -> this is where I will need to click the item to display in the cart.
<div class="col-sm-12">
<?php echo $this->Form->create('Cart',array('id'=>'add-form','url'=>array('controller'=>'carts','action'=>'add')));?>
<ul class="list-inline">
<?php foreach ($side_dish as $sidedish):?>
<li>
<?php echo $this->Form->hidden('product_id',array('value'=>$sidedish['Sidedish']['sidedish_id'])); ?>
<?php
echo $this->Form->submit(//$sidedish['Sidedish']['sidedish_id'],
'',array(
'name'=>'submit',
'style'=>'height:130px;width:200px;'
. 'background-repeat:no-repeat;'
. 'border:none;'
. 'background-image:url(/webapp' .$sidedish['Sidedish']['sidedish_img']. ')'));
?>
<h5 class="text-center"><?php echo $sidedish['Sidedish']['sidedish_name'];?></h5>
<h5 class="text-center">$<?php echo $sidedish['Sidedish']['sidedish_price'];?></h5>
</li>
<?php endforeach;?>
</ul>
<?php echo $this->Form->end();?>
</div>
Some people told me that the problem is the foreach loop in my views/orders.ctp and some people told me that the problem is in the controller. I'm not sure where is the problem here. please need help guys.
Can you please show your code for this function $this->Cart->addProduct()?
<?php
App::uses('AppModel', 'Model');
App::uses('CakeSession', 'Model/Datasource');
class Cart extends AppModel {
public $useTable = false;
/*
* add a product to cart
*/
public function addProduct($productId) {
$allProducts = $this->readProduct();
if (null!=$allProducts) {
if (array_key_exists($productId, $allProducts)) {
$allProducts[$productId]++;
} else {
$allProducts[$productId] = 1;
}
} else {
$allProducts[$productId] = 1;
}
$this->saveProduct($allProducts);
}
/*
* get total count of products
*/
public function getCount() {
$allProducts = $this->readProduct();
if (count($allProducts)<1) {
return 0;
}
$count = 0;
foreach ($allProducts as $product) {
$count=$count+$product;
}
return $count;
}
/*
* save data to session
*/
public function saveProduct($data) {
return CakeSession::write('cart',$data);
}
/*
* read cart data from session
*/
public function readProduct() {
return CakeSession::read('cart');
}
}
I am having a problem. Please let me know if there is a solution. I am new to codeigniter therefore, sorry in advance if there is a silly one!
I am trying to fetch data from a database. Table name is fw_main_cat which have fields (cat_id, cat_parent_id, cat_level, cat_title, cat_menu_order and cat_status). cat_id is unique.
I want a dropdown menu (in view) to take all the data of a column cat_title through cat_level (which are int). So, how can I do?
Here is my code which I have tried so far.
This is Model :
public function cat_level_one($cat_level)
{
$sql = "Select * from fw_main_cat Where cat_level=? ";
$result = $this->db->query($sql, $cat_level);
if($result->num_rows() > 0)
{
return $result->result_array();
}
else { return false;
}
}
This is Controller :
public function getcategory()
{
if ($this->session->userdata('session_status'))
{
$cat_level_one = $this->admin_cat_model->cat_level_one($cat_level);
$data['cat_level_one'] = $this->admin_cat_model->cat_level_one($cat_level);
$this->session->set_userdata('cat_level', $_POST['cat_level']);
$this->laod_view('admin_view/admin_cat/view_add_category', $data);
}else {
redirect ('admin_view/admin_cat/view_category');
}
}
This is View (dropdown menu):
<li class="full-row">
<select name = 'cat_level_one' id = 'cat_level_one'>
<option value="<?php if(isset ($cat_level_one) && $cat_level_one != ''){ foreach ($cat_level_one as $cat_one){ echo $cat_one->cat_id; } } ?>"
selected="selected">------------Select Category------------</option>
Thanks! for the consideration.
Updated code -
// in model
function cat_level_one($cat_level)
{
$this->db->where('cat_level',$cat_level);
$q = $this->db->get('fw_main_cat');
$data = $q->result_array();
return $data;
}
//controller function
public function getcategory()
{
**if ($this->session->userdata('session_status'))
{
$data['cat_level_one'] = $this->admin_cat_model->cat_level_one($cat_level);**
//Where this post data comes from??
$this->session->set_userdata('cat_level', $_POST['cat_level']);
$this->laod_view('admin_view/admin_cat/view_add_category', $data);
}else {
redirect ('admin_view/admin_cat/view_category');
}
}
//in view
<li class="full-row">
<select name = 'cat_level_one' id = 'cat_level_one'>
<option value="">-- Select Category --</option>
<?php foreach($cat_level_one as $cat_one){ ?>
<option value="<?php echo $cat_one->cat_id; ?>"><?php echo $cat_one->cat_title; ?></option>
<?php } ?>
</select>
</li>
I have used a component for uploading image,there is no problem in controller after add component.Here the code
class OesUsersController extends AppController {
var $helpers = array('Html', 'Form');
var $components = array('upload');
public function index() {
}
public function upload()
{
if (empty($this->data))
{
$this->render();
}
else
{
$this->cleanUpFields();
// set the upload destination folder
$destination = realpath('../../app/webroot/img/uploads/') . '/';
// grab the file
$file = $this->data['Image']['filedata'];
// upload the image using the upload component
$result = $this->Upload->upload($file, $destination, null, array('type' => 'resizecrop', 'size' => array('400', '300'), 'output' => 'jpg'));
if (!$result){
$this->data['Image']['filedata'] = $this->Upload->result;
} else {
// display error
$errors = $this->Upload->errors;
// piece together errors
if(is_array($errors)){ $errors = implode("<br />",$errors); }
$this->Session->setFlash($errors);
$this->redirect('/images/upload');
exit();
}
if ($this->Image->save($this->data)) {
$this->Session->setFlash('Image has been added.');
$this->redirect('/images/index');
} else {
$this->Session->setFlash('Please correct errors below.');
unlink($destination.$this->Upload->result);
}
}
}
The problem is image doesn't come from add.ctp
here the add.ctp code
<label for="Image">Image:</label>
<input type="file" name="data[Image][filedata]" id="ImageFiledata" />
add function code
public function add() {
$clint_ip=$this->request->clientIp();
if ($this->request->is('post')) {
$this->OesUser->create();
pr($this->request->data);
$this->request->data['OesUser']['user_otpkey']=String::uuid();
$this->request->data['OesUser']['user_regdate']=date("Y-m-d H:i:s");
$this->request->data['OesUser']['user_ip']=$clint_ip;
$this->barcode($this->request->data['OesUser']['user_otpkey']);
if ($this->OesUser->save($this->request->data)) {
$this->Session->setFlash(__('The oes user has been saved'), 'flash_success');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The oes user could not be saved. Please, try again.'), 'flash_fail');
}
}
$this->set('ip',$clint_ip);
}
here, database field name: image
controller name :OesUsers
Model name :OesUser
for full work I have taken help from this link
http://labs.iamkoa.net/2007/10/23/image-upload-component-cakephp/
How is your entire form looks like in add.ctp?
It sounds to me that you did not add
enctype="multipart/form-data"
to the form. That will cause the form not to post the file.
And also, it is recommended to use Form helper to create form.
When using Form helper, specify the form type to file
$this->Form->create('model',array('type'=>'file'));