Incrementing Shared Value in Database - php

I want to create a polling system where user can select radio button and the choice will be incrementing in database
insert_view.php - Simple form insertion for selecting the required fields
<html>
<body>
<?php echo form_open('insert_ctrl'); ?>
<h1>Insert Data Into Database Using CodeIgniter</h1><hr/>
<?php if (isset($message)) { ?>
<CENTER><h3 style="color:green;">Data inserted successfully</h3></CENTER> <br>
<?php } ?>
<?php echo "which language do you prefer..?";?><br/>
<?php echo form_radio(array('id' => 'rad1', 'name' => 'rad1','value'=>0)); ?>
<?php echo form_label('JAVA'); ?> <?php echo form_error('rad1'); ?><br />
<?php echo form_radio(array('id' => 'rad2', 'name' => 'rad2','value'=>0)); ?>
<?php echo form_label('PHP'); ?> <?php echo form_error('rad2'); ?><br />
<?php echo form_radio(array('id' => 'rad3', 'name' => 'rad3','value'=>0)); ?>
<?php echo form_label('C\C++'); ?> <?php echo form_error('rad3'); ?><br />
<?php echo form_radio(array('id' => 'rad4', 'name' => 'rad4','value'=>0)); ?>
<?php echo form_label('DOTNET'); ?> <?php echo form_error('rad4'); ?><br />
<?php echo form_submit(array('id' => 'submit', 'value' => 'Submit')); ?>
</body>
</html>
insert_ctrl.php - for sending the request through the help of controller from the view to the model.
<?php
class insert_ctrl extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->model('insert_model');
}
function index() {
$data = array(
'Option1' => $this->input->post('rad1'), //for selecting the required option
'Option2' => $this->input->post('rad2'), //for selecting the required option
'Option3' => $this->input->post('rad3'), //for selecting the required option
'Option4' => $this->input->post('rad4')
);
$vote = $this->input->post('Submit');
if($vote=="Option1"){
$value=$value+1;
}
elseif($vote=="Option2"){
$value=$value+1;
}
elseif($vote=="Option3"){
$value=$value+1;
}
elseif($vote=="Option4"){
$value=$value+1;
}
//Setting values for tabel columns
//Transfering data to Model
$this->insert_model->form_insert($data);
//$data['message'] = 'Data Inserted Successfully';
//Loading View
$this->load->view('insert_view', $data);
}
}
?>
insert_model.php
<?php
class insert_model extends CI_Model{
function __construct() {
parent::__construct();
}
function form_insert($data){
// Inserting in Table(students) of Database(college)
$this->db->insert('students', $data);
}
}
?>

Class name should start with capital letter,
class Insert_ctrl extends CI_Controller {
If the value to be incremented is in same table,then pass the value to model,
$data['value'] = $value;
$this->insert_model->form_insert($data);
And first of all what is the value of $value.??
If the value is present in different table,increment like this,
Update table name set value = value + 1 where question_id = id.
Instead of so many if else,
if($vote=="Option1" || $vote=="Option2" || $vote=="Option3" || $vote=="Option4"){
$value=$value+1;
}

Related

codeigniter form data is not inserting into MSSQL database

I have a simple form setup. It shows up fine and when I hit submit looks like it is working, but when I go to check the datat in MSSQL Server it is not there. I am not sure why it is not working.
Controller is insert.php
<?php
class insert extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('insert_model');
}
function index()
{
// Including Validation Library
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
// Validating Name Field
$this->form_validation->set_rules('EmpName', 'Employee_Name', 'required|min_length[3]|max_length[15]');
// Validating Email Field
$this->form_validation->set_rules('Department', 'Department', 'required|min_length[3]|max_length[15]');
// Validating Email Field
$this->form_validation->set_rules('LanID', 'LanID', 'required|min_length[3]|max_length[15]');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('insert_view');
}
else
{
// Setting Values For Tabel Columns
$data = array(
'Employee_Name' => $this->input->post('EmpName'),
'Department' => $this->input->post('Department'),
'LanID' => $this->input->post('LanID'),
);
// Transfering Data To Model
$this->insert_model->form_insert($data);
// Loading View
$this->load->view('insert_view');
}
}
}
?>
Model is insert_model.php
<?php
class insert_model extends CI_Model{
function __construct() {
parent::__construct();
}
function form_insert($data){
// Inserting in Table(requests) of Database(employee)
$this->db->insert('requests', $data);
}
}
?>
View is insert_view.php
<html>
<head>
<title>Insert Data Into Database Using CodeIgniter Form</title>
</head>
<body>
<div id="container">
<?php echo form_open('insert'); ?>
<h1>Insert Data Into Database Using CodeIgniter</h1>
<?php echo form_label('Employee Name :'); ?> <?php echo form_error('EmpName'); ?>
<?php echo form_input(array('id' => 'EmpName', 'name' => 'EmpName')); ?>
<?php echo form_label('Department :'); ?> <?php echo form_error('Department'); ?>
<?php echo form_input(array('id' => 'Department', 'name' => 'Department')); ?>
<?php echo form_label('LanID :'); ?> <?php echo form_error('LanID'); ?>
<?php echo form_input(array('id' => 'LanID', 'name' => 'LanID')); ?>
<?php echo form_submit(array('id' => 'submit', 'value' => 'Submit'));?>
<?php echo form_close(); ?>
</div>
</body>
</html>
have you tried debugging?
in your controller:
$data = array(
'Employee_Name' => $this->input->post('EmpName'),
'Department' => $this->input->post('Department'),
'LanID' => $this->input->post('LanID'),
);
does all array index matches exactly with your database table's column name?
in your model:
print_r($data);
before:
$this->db->insert('requests', $data);
if $data contains data, try set function.
$this->db->set('Employee_Name', $EmpName);
$this->db->set('Department', $Department);
$this->db->set('LanID', $LanID);
$this->db->insert('requests');
try debugging...

How to get the id from the url then insert it into the data base using codeigniter

Hopefully all this info helps out.
So what I am doing is i have a forum page that I have set up to were you can select a category, from that category you can insert a post into that category. What I need help with is getting the id of that category for the database so that post will show up when I echo it out. In other words linking ids to the pages upon insert.
ok so i know that its inserting the username message title ect but what its not doing is getting the 1 from the url and inserting that 1 into the database under category_id
Here is my url I left out the main http to shorten this up but the rest of it were the number 1 is what I am wanting to get and insert cause that its going to change depending on the category you choose. index.php/forum/create_post/1
This is what my category table has
ID title
1 community
This is what my post table has were all the main info comes from and were I am wanting to connect the category_id to the main category table.
id, title message date user id category_id flaged username
This is the first view that will insert the new post
View:
<div id="container">
<div class="module">
<?php echo form_open('forum/create_post'); ?>
<div>
<?php
echo form_label('Title', 'title');
echo form_input('title', '');
?>
</div>
<div>
<?php
echo form_label('Message', 'message');
echo form_input('message', '');
?>
</div>
<div>
<?php echo form_submit('create', 'create new post'); ?>
</div>
<?php echo form_close(); ?>
</div>
</div>
Controller: here is the section in the controller were I am passing all my input if no to
public function create_post() {
if( !$this->session->userdata('username') ) {
redirect('/'); // please login to continue
}
if( $this->input->post('create') ) {
$this->forum->createpost(array(
// $id= $this->uri->segment(3),
'title' => $this->input->post('title'),
'message' => $this->input->post('message'),
'user_id'=> $this->session->userdata('id'),
'username'=>$this->session->userdata('username'),
));
}
$this->load->view('templates/header');
$this->load->view('forum/create_post');
$this->load->view('templates/footer');
}
Here is the model that i'am inserting the data to
public function createpost($data){
$this->db->insert('post',$data);
}
As per your URL index.php/forum/create_post/1, You controller function should be as below to meet CI Standard.
public function create_post($category_id) {
So you can access $category_id directly. No need to get url segment.
$res = $this->forum->createpost(array(
$id= $category_id,
'title' => $this->input->post('title'),
'message' => $this->input->post('message'),
'user_id'=> $this->session->userdata('id'),
'username'=>$this->session->userdata('username'),
));
if($res)
{
// show thanks msg
}
else
{
// show error msg
}
In your model:
You can check that data is inserted
public function createpost($data)
{
$this->db->insert('post',$data);
if($this->db->affected_rows()>0)
return true;
else
return false;
}
You are not sending /1 to the page again. Your form must send that /1 from original url.
<?php echo form_open('forum/create_post'); ?>
create_post method wont receive a 3rd segment, because it doesn't exists. Store category id in a input hidden and access it by $this->input->post('category_id'):
Controller
public function create_post() {
if( !$this->session->userdata('username') ) {
redirect('/'); // please login to continue
}
if( $this->input->post('create') ) {
$this->forum->createpost(array(
'category_id' => $this->input->post('category_id'),
'title' => $this->input->post('title'),
'message' => $this->input->post('message'),
'user_id' => $this->session->userdata('id'),
'username'=>$this->session->userdata('username')
));
}
$data['category_id'] = $this->uri->segment(3);
$this->load->view('templates/header');
$this->load->view('forum/create_post', $data);
$this->load->view('templates/footer');
}
View
<div id="container">
<div class="module">
<?php echo form_open('forum/create_post'); ?>
<div>
<?php
echo form_label('Title', 'title');
echo form_input('title', '');
?>
</div>
<div>
<?php
echo form_label('Message', 'message');
echo form_input('message', '');
?>
</div>
<div>
<?php echo form_submit('create', 'create new post'); ?>
</div>
<input type="hidden" name="category_id" value="<?php echo $category_id; ?>">
<?php echo form_close(); ?>
</div>
</div>
Also, ask yourself if there is a need to storage user ID and username. Isn't username attached to an ID? Couldn't it be retrieved by just selecting userID from a post?
I found out what i needed to do make this all work i had to insert the uri segment into a hidden input forum to get it to insert into the right id box and now iam able to connect the right categorys

Update two models of different databases with single view in yii

I have a view (_form.php) with fields (name,summary) submit button. If I click on submit button, it should update Name field of One model and Summary field of another model.Both this models are of different databases.
Can anyone help on this. I tried the following for this
In _form.php(Test)
<?php echo $form->labelEx($model, ‘name’); ?>
<?php echo $form->textField($model, ‘name’, array(‘size’ => 60, ‘maxlength’ => 250)); ?>
<?php echo $form->error($model, ‘name’); ?>
<?php echo $form->labelEx(Test1::model(), ‘summary’); ?>
<?php echo $form->textField(Test1::model(), ‘summary’, array(‘size’ => 60, ‘maxlength’ => 250)); ?>
<?php echo $form->error(Test1::model(), ‘summary’); ?>
<?php echo CHtml::submitButton($model->isNewRecord ? ‘Create’ : ‘Save’); ?>
In TestController.php
public function actionCreate() {
$model = new Test;
if (isset($_POST['Test'])) {
$model->attributes = $_POST['Test'];
if ($model->save()) {
$modeltest1 = new Test1;
$modeltest1->attributes = $_POST['Test1'];
$modeltest1->Id = $model->Id;
if ($modeltest1->save())
$this->redirect(array('view', 'Id' => $model->Id));
}
}
$this->render('create', array(
'model' => $model,
));
}
This code is not working. How can I make it work for different databases. I followed the below link for this.
http://www.yiiframework.com/wiki/291/update-two-models-with-one-view/
This code actually should work, but its bad.
I assume that you dont understand at all what is model and what its doing in Yii, also how to render and create forms.
I'll try to explain how it should be.
1st of all dont use Test::model() in views, unless you want to call some function from it(but try to avoid it). It can be done by passing it from controller:
public function actionCreate() {
$model_name = new Name;
$model_summary=new Summary;
//something here
$this->render('create', array(
'name' => $model_name,
'summary'=>$model_summary,
));
}
When you make render you passing variables to your view (name_in_view=>$variable)
2nd. In your view you can use your variables.
<?php echo $form->labelEx($name, ‘name’);
echo $form->textField($name, ‘name’, array(‘size’ => 60, ‘maxlength’ => 250));
echo $form->error($name, ‘name’);
echo $form->labelEx($summary, ‘summary’);
echo $form->textField($summary, ‘summary’, array(‘size’ => 60, ‘maxlength’ => 250)); ?>
echo $form->error($summary, ‘summary’); ?>
echo CHtml::submitButton($model->isNewRecord ? ‘Create’ : ‘Save’); ?>
3rd. You need to understand what is model. It's class that extends CActiveRecord in this case. Your code in controller should loo like:
public function actionCreate() {
$model_name = new Name;
$model_summary=new Summary;
if (isset($_POST['Name']))
$model_name->attributes=$_POST['Name'];
if (isset($_POST['Summary']))
$model_name->attributes=$_POST['Summary'];
if ($model_name->save()&&$model_summary->save())
$this->redirect(array('view', 'Id' => $model->Id));
$this->render('create', array(
'name' => $model_name,
'summary'=>$model_summary,
));
}
$model->attributes=$_POST[] here is mass assignment of attributes, so they must be safe in rules. You always can assign attributes with your hands (1 by 1), or form an array and push it from array.

zf2 form validation (zfcAdmin and BjyAuthorize related)

I'm facing validation problems integrating my custom module in zfcAdmin and BjyAuthorize.
My form class:
...
$formOptions = $this->settings->getFormSettings();
foreach ($formOptions as $field){
if (isset($field['field']))
$this->add($field['field']);
}
...
My filter class:
$formOptions = $this->settings->getFormSettings();
foreach ($formOptions as $filter){
if (isset($filter['filter']))
$this->add($filter['filter']);
}
...
Fields, filters and other options are retrieved from config file.
Basically everything works fine: form data can be added, edited or deleted from db.
Also after the zfcAdmin module installation no problem rose. Everything works fine using both 'site/mymodule' route and 'site/admin/mymodule' route: i can still add, edit and delete items from db.
Here the problem: I need some form elements (a Select in this particular case) editable/viewable only by administrator. (I can write a new controller/entity class 'ad hoc' for admin but i would like to use the same code for the whole site.)
I installed and configured bjyoungblood/BjyAuthorize module: it allowed me to display some form elements/fields only to admin but when i'm in edit mode a form validation error is displayed: "Value is required and can't be empty"
Here the code:
//view/mymodule/mymodule/update.phtml
<div id="page" style="margin-top: 50px;">
<?php if (isset($this->messages) && count($this->messages) > 0 ): ?>
<?php foreach ($this->messages as $msg): ?>
<div class="alert alert-<?php echo $this->escapeHtmlAttr($msg['type']); ?>">
<?php if (isset($msg['icon'])) echo '<i class="'.$this->escapeHtmlAttr($msg['icon']).'"></i> '; ?><?php echo $this->escapeHtml($msg['message']); ?>
</div>
<?php endforeach; ?>
<?php endif; ?>
<?php
$title = 'Edit Item';
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>
<?php
$form = $this->form;
$form->setAttribute('action', $this->url($this->route . 'mymodule/update', array('action' => 'update', 'id' => $this->id )));
$form->prepare();
$form->setAttribute('method', 'post');
$input = $form->getInputFilter();
?>
<?php echo $this->form()->openTag($form) ?>
<dl class="zend_form">
<?php foreach ($form as $element): ?>
<?php
//CHECK USER PRIVILEDGES
$elName = $element->getName();
$elResource = isset($this->form_options[$elName]['auth']) ? $this->form_options[$elName]['auth']['resource'] : "userresource";
$elPrivilege = isset($this->form_options[$elName]['auth']) ? $this->form_options[$elName]['auth']['privilege'] : "view";
//SHOW THE ELEMENT IF ALLOWED
if($this->isAllowed($elResource, $elPrivilege)):
?>
<?php if ($element->getLabel() != null): ?>
<dt><?php echo $this->formLabel($element) ?></dt>
<?php endif ?>
<?php if ($element instanceof Zend\Form\Element\Button): ?>
<dd><?php echo $this->formButton($element) ?></dd>
<?php elseif ($element instanceof Zend\Form\Element\Select): ?>
<dd><?php echo $this->formSelect($element) . $this->formElementErrors($element) ?></dd>
<?php else: ?>
<dd><?php echo $this->formInput($element) . $this->formElementErrors($element) ?></dd>
<?php endif ?>
<?php else: ?>
<?php
?>
<?php endif ?>
<?php endforeach ?>
</dl>
<?php echo $this->form()->closeTag() ?>
</div>
<div class="clear-both"></div>
My controller action
//controller
public function updateAction(){
$messages = array();
$id = (int)$this->getEvent()->getRouteMatch()->getParam('id');
$form = $this->getServiceLocator()->get('FormItemService');
$itemMapper = $this->getItemMapper();
$item = $itemMapper->findById($id);
$form->bind($item);
$request = $this->getRequest();
if($request->isPost()){
$form->setData($request->getPost());
if ($form->isValid()) {
die('c');//never here
$service = $this->getServiceLocator()->get('mymodule\Service\Item');
if ( $service->save($form->getData()) )
{
$messages[] = array(
'type' => 'success',
'icon' => 'icon-ok-sign',
'message' => 'Your profile has been updated successfully!',
);
}
else
{
$messages[] = array(
'type' => 'error',
'icon' => 'icon-remove-sign',
'message' => 'Profile update failed! See error messages below for more details.',
);
}
}else{
var_dump($form->getMessages());//Value is required and can't be empty
}
}
return array(
'messages' => $messages,
'form' => $form,
'id' => $id,
'form_options' => $this->getServiceLocator()->get('mymodule_module_options')->getFormSettings(),
'route' => $this->checkRoute($this->getEvent()->getRouteMatch()->getmatchedRouteName())
);
}
If user is not allowed to view the resource, the element is not echoed. So $request->getPost() has no value for that form element and an error is returned by isValid().
Has anyone solved a similar problem or can anyone point me to the right direction?
Thanks
The problem is that you don't do any security check in your FormFilter class, where you define your required fields.
The $form->isValid() function checks the posted data against those filter elements. So it's not enough to prevent the 'echo field' in your view, you still need to apply the security check to the filter element.
One other approach would be to make two forms one for the front end and one for the admin. Since the one for the admin will have the same fields plus one extra select field you can make the admin form extends the front end one. E.g.
class myForm
{
public function __construct(...)
{
// add fields and set validators
}
}
and the admin form could be:
class MyAdminForm extends myForm
{
public function __construct(...)
{
parent::__construct(...);
// add the extra field and extra validator
}
}
In that way even if you edit the front end form (or validators) the back end will always be up to date.
Hope this helps :),
Stoyan

insert query is not working in cake php

this is action url: http://localhost/carsdirectory/users/dashboard.
dashboad.ctp (i have select filed and in this select field i m fetching data from that filed car_type and table name car_types)
<?php echo $this->Form->create('User', array('type' => 'file', 'action' => 'dashboard')); ?>
<label class="ls-details-label">Type</label>
<div class="ls-details-box">
<?php
foreach ($car_types as $car_type)
{
$car_type_new[$car_type['Car_type']['id']]=
$car_type['Car_type']['car_type'];
}
echo $this->Form->input('car_type',
array( 'label'=>false,
'options'=>$car_type_new,
'empty'=>' Select ',
'class'=>'styledselect_form_1'));
?>
</div>
<?php echo $this->Form->end(array('label' => 'Submit',
'name' => 'Submit',
'div' => array('class' => 'ls-submit')));?>
users_controller.php (controller)
class UsersController extends AppController{
var $name = "Users";
public function dashboard(){
$this->loadModel('Car_type'); // your Model name => Car_type
$this->set('car_types', $this->Car_type->find('all'));
if(!empty($this->data))
{
$this->loadModel('Car');
if($this->Car->save($this->data))
{
$this->Session->setFlash('Detail has Been Saved');
$this->redirect(array('action'=>'dashboard'));
}
else
{
$this->Session->setFlash('Detail could not save');
}
}
}
car.php (model)
<?php
class Car extends appModel{
var $name = "Car";
}
?>
i want to inset data car_type_id field in (table name cars) , but i m not able to do it
so plz help me
thanks in advance, vikas tyagi
You may try this:
echo $this->Form->input('Car.car_type_id', array(...));

Categories