how to insert values in table in cake php - php

here i done code for contact us page with two fileds like email,body it stores values in db
but it s not working i post the code here
Model
//model/pages.php
<?php
class pages extends AppModel{
var $useTable = 'contact';
}
?>
Controller
class PagesController extends AppController {
public $uses = array();
public function display() {
$path = func_get_args();
$count = count($path);
if (!$count) {
return $this->redirect('/');
}
$page = $subpage = $title_for_layout = null;
if (!empty($path[0])) {
$page = $path[0];
}
if (!empty($path[1])) {
$subpage = $path[1];
}
if (!empty($path[$count - 1])) {
$title_for_layout = Inflector::humanize($path[$count - 1]);
}
$this->set(compact('page', 'subpage', 'title_for_layout'));
try {
$this->render(implode('/', $path));
} catch (MissingViewException $e) {
if (Configure::read('debug')) {
throw $e;
}
throw new NotFoundException();
}
}
public function index(){
$this->set('post', $this->contact->find('all'));
}
public function create() {
if ($this->request->is('post'))
//this function for methods like get, post, set,delelte
{
// print_r('post');
$this->contact->create();
if ($this->contact->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been saved.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to add your post.'));
}
}
}
view
here code for display
view/contact.ctp
<?php
echo 'welcome to Contact us';
echo $this->Form->create('pages');
echo $this->Form->input('email');
echo $this->Form->input('body', array('rows' => '6'));
echo $this->Form->end('Save pages');
?>
added in db table and values contact

Did you read something to start in CakePHP like Getting Started or CakePHP Conventions?
Reading some documentation, you will find that your tables should be named in plural and models in singular. Your model in app/Model/Contact.php looks like this:
class Contact extends AppModel {
public $useTable = 'contacts'; // It is not necessary, because CakePHP implicitly understands that your table will be in the plural
}
Now, your view located in app/View/Contacts/index.ctp:
echo $this->Form->create('Contact');
echo $this->Form->input('email');
echo $this->Form->input('body', array('rows' => '6'));
echo $this->Form->end('Save');
And your controller in app/Controller/ContactsController.php:
class ContactsController extends AppController {
public function index() {
if ($this->request->is('post')) {
$this->Contact->create();
if ($this->Contact->save($this->request->data)) {
$this->Session->setFlash(__('Your contact has been saved.'));
} else {
$this->Session->setFlash(__('Unable to add your contact.'));
}
}
}
}
This is a basic usage. I recommend you read the documentation to start with CakePHP because it has lots of interesting things that you may need.

Related

Edit in CakePHP creates new entry instead of updating old one

I tried to follow the CakePHP blog tutorial (http://book.cakephp.org/2.0/en/tutorials-and-examples/blog/blog.html) and everything works fine, except for the edit method. The edit function as specified in the tutorial seems to work, but instead of updating the old entry, it creates a new entry in the database. (But says that it did update the old entry with the "Jop was updated" message)
My source files are:
edit.ctp
<html>
<!-- File: /app/View/Jobs/edit.ctp -->
<h1>Edit Job</h1>
<?php
echo $this->Form->create('Job');
echo $this->Form->input('type');
echo $this->Form->input('name');
echo $this->Form->input('company');
echo $this->Form->input('id', array('type' => 'hidden'));
echo $this->Form->end('Save Job');
?>
</html>
JobsController.php
class JobsController extends AppController
{
public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session');
public function index()
{
$this->set('jobs', $this->Job->find('all'));
}
public function view($id=null) {
if (!$id)
{
throw new NotFoundException(__('Invalid job'));
}
$job = $this->Job->findById($id);
if (!$job)
{
throw new NotFoundException(__('Invalid job'));
}
$this->set('job', $job);
}
public function add() {
if ($this->request->is('POST')) {
$this->Job->create();
if ($this->Job->save($this->request->data))
{
$this->Session->setFlash(__('Your job has been saved.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash('Unable to add your job.');
}
}
public function edit($id=null) {
if (!$id) {
throw new NotFoundException(__('Invalid job'));
}
$job = $this->Job->findById($id);
if (!$job) {
throw new NotFoundException(__('Invalid job'));
}
if ($this->request->is(array ('POST', 'PUT'))) {
$this->Job->id = $id;
if ($this->Job->save($this->request->data)) {
$this->Session->setFlash(__('Job has been updated.'));
return $this->redirect(array('action' => 'index'));
}
else {
$this->Session->setFlash(__('Unable to update the job.'));
}
if (!$this->request->data) {
$this->request->data = $job;
}
}
}
public function delete($id) {
if (!$id) {
throw new NotFoundException(__('Invalid job'));
}
if ($this->request->is('GET')) {
throw new MethodNotAllowedException();
}
if ($this->Job->delete($id)) {
$this->Session->setFlash(__('Job has been deleted.'));
}
else {
$this->Session->setFlash(__('Unable to delete job.'));
}
return $this->redirect(array('action' => 'index'));
}
}
?>
If someone else has this problem, this is the solution that worked for me:
if (!$this->request->data) {
$this->request->data = $job;
}
was indented wrong, it shouldn't be within the
if ($this->request->is(array ('POST', 'PUT')))
block, but on the same level, i.e. one layer less indented.
Please check your edit.ctp page you are missing some.
<?php echo $this->Form->create('Job'); ?>
<?php
echo $this->Form->hidden('id', array('value' => $this->data['Job']['id'])); ?>

codeigniter - Selecting data from database

Sorry for the basic question, but I couldn't fidn the answer anywhere online. I started with codeigniter yesterday And all I am trying to do is selecting data from my database. However I don't get any errors nor does it show any data. If i change the database tabel name. It immediately throws an error.
Model
<?php
class Customer_model extends CI_Model {
public function get_customers($id) {
if ($id != FALSE) {
$query = $this->db->get_where('customer', array('id' => $id));
} else {
return FALSE;
}
}
}
Controller
<?php
class Customer extends CI_Controller {
public function show($id) {
$this->load->model('customer_model');
$news = $this->customer_model->get_customers($id);
$data['customer_name'] = $news['customer_name'];
$data['streetname'] = $news['streetname'];
$this->load->view('customers', $data);
}
}
VIEW
<?php echo "hallo"; ?>
<?php echo $customer_name; ?>
** EDIT, in my page is can see the echo of hello. So I am in the correct page, but there are no errors nor notices of any data missing.
If anyone have any idea what I'm doing wrong, thanks a zillion. btw database connectivity is included and also the package is loaded.
thanks
In Model
class Customer_model extends CI_Model {
public function get_customers($id) { # refactored
$this->db->select(*);
$query = $this->db->get_where('customer', array('id' => $id));
$result = $query->result_array();
$count = count($result);
if(empty($count)){
return false;
}
else{
return $result;
}
}
}
In Controller
class Customer extends CI_Controller {
public function show($id) {
if(empty($id)) # Added
{
echo "Token Invalid";
}
else{
$this->load->model('customer_model');
$news = $this->customer_model->get_customers($id);
if($news == false){ # Added
echo "No result Found";
}
else{
$data['customer_name'] = $news[0]['customer_name']; # Changed
$data['streetname'] = $news[0]['streetname']; # Changed
$this->load->view('customers', $data);
}
}
}
}

php yii unable to login using useridentity component

Here is my authentication controller
class AuthController extends Controller
{
public function actionLogin()
{
$model = new LoginForm;
$post = Yii::app()->request->getPost('LoginForm');
// If form is submitted
if($post) {
$identity = new UserIdentity($post['username'], $post['password']);
if($identity->authenticate()) { // loop enters but could not get id
echo Yii::app()->user->id;
echo Yii::app()->user->getId();
} else {
echo 'failed';
}
//exit;
}
$this->render('login', array('model' => $model));
}
}
Here is my UserIdentity.php
class UserIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
$user = SchLogins::model()->findByAttributes(array('username' => $this->username));
if(is_null($user)) {
$this->errorCode=self::ERROR_USERNAME_INVALID;
} else if($user->password != $this->password) {
$this->errorCode=self::ERROR_PASSWORD_INVALID;
} else {
$this->_id = $user->id;
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId()
{
return $this->_id;
}
}
In the above code I am having problem in getting user id (i.e) Yii::app()->user->getId(); this returns nothing and what wrong I did the above code
You are creating a LoginForm instance $model but you never use it to actually login. If you are using the standard LoginForm model then it is what interacts with the UserIdentity class. It should be this:
if($post) {
$model->attributes = $_POST['LoginForm'];
if ($model->validate() && $model->login()) { // loop enters but could not get id
echo Yii::app()->user->id;
echo Yii::app()->user->getId();
} else {
echo 'failed';
}
//exit;
}
If you look at the login() function of LoginForm you will see it calls Yii::app()->user->login($this->_identity,$duration); which is what actually sets the Yii::app()->user which with your method was being skipped.

CakePHP DB field update fail

I am using cakePHP why won't the name insert into the table, a null value seams to be passed as the table is updated but with out the name?
Table in Database
CREATE TABLE tests (
id serial not null unique primary key,
name varchar,
created timestamp default CURRENT_TIMESTAMP
)
add.ctp
<?php
echo $this->Form->create('Post');
echo $this->Form->input('name');
echo $this->Form->end('RSVP');
?>
Test Model
<?php
class Test extends AppModel {
var $name = 'Test';
}
TestContoller
<?php
class TestController extends AppController {
public $helpers = array('Html', 'Form');
var $name = "Test";
public function index() {
$this->set('tests', $this->Test->find('all'));
}
public function view($id = null) {
$this->Test->id = $id;
$this->set('Test', $this->Test->read());
}
public function add() {
if ($this->request->is('post')) {
if ($this->Test->save($this->request->data)) {
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
}
else {
$this->Session->setFlash('Unable to add your post.');
}
}
}
public function edit($id = null) {
$this->Test->id = $id;
if ($this->request->is('get')) {
$this->request->data = $this->Post->read();
}
else {
if ($this->Test->save($this->request->data)) {
$this->Session->setFlash('Your post has been updated.');
$this->redirect(array('action' => 'index'));
}
else {
$this->Session->setFlash('Unable to update your post.');
}
}
}
public function delete($id) {
if ($this->request->is('get')) {
throw new MethodNotAllowedException();
}
if ($this->Test->delete($id)) {
$this->Session->setFlash('The post with id: ' . $id . ' has been deleted.');
$this->redirect(array('action' => 'index'));
}
}
}
In your method you missed to include $this->Test->create();, which will add new row to table and inset new data to it.
public function add() {
if ($this->request->is('post')) {
$this->Test->create(); // missed this line
if ($this->Test->save($this->request->data)) {
$this->Session->setFlash('Your post has been saved.');
$this->redirect(array('action' => 'index'));
}
else {
$this->Session->setFlash('Unable to add your post.');
}
}
}

Real-world testing of CakePHP controllers?

I'm writing a new application with CakePHP (just-released 1.2.4), using SimpleTest 1.0.1. I have read the relevant sections of the Cookbook, searched on the Bakery, and read Mark Story's postings on controller testing (the hard way and with mocks).
Unfortunately, none of this talks about real-world testing of non-trivial controllers. Lots of apps put areas of the site behind a login, yet I cannot figure out how to test the simple scenario of:
guest access to protected page redirects?
valid credentials sets expected session variables?
invalid credentials re-displays login page with error message?
The controller and test below do not work as I thought they would. Both assertions fail and I also get a PHP error:
FAILED
[NULL] should not be null at [.../app/tests/cases/controllers/users_controller.test.php line 79]
.../app/tests/cases/controllers/users_controller.test.php -> UsersControllerTest -> testLogin
FAILED
Equal expectation fails as [NULL] does not match [Integer: 1] at [.../app/tests/cases/controllers/users_controller.test.php line 80]
.../app/tests/cases/controllers/users_controller.test.php -> UsersControllerTest -> testLogin
ERROR
Unexpected PHP error [Undefined index: action] severity [E_NOTICE] in [.../cake/libs/controller/components/auth.php line 266]
.../app/tests/cases/controllers/users_controller.test.php -> UsersControllerTest -> testLogin
Here is the controller (baked plus Mark Story's "hard way" testing method):
class UsersController extends AppController
{
var $name = 'Users';
var $helpers = array('Html', 'Form');
var $components = array('Auth');
function login()
{
}
function logout()
{
$this->redirect($this->Auth->logout());
}
function index()
{
$this->set('users', $this->paginate());
}
function view($id = null)
{
if (!$id)
{
$this->Session->setFlash(__('Invalid User.', true));
$this->redirect(array('action'=>'index'));
}
$this->set('user', $this->User->read(null, $id));
}
function add()
{
if (!empty($this->data))
{
$this->User->create();
if ($this->User->save($this->data))
{
$this->Session->setFlash(__('The User has been saved', true));
$this->redirect(array('action'=>'index'));
}
else
{
$this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
}
}
}
function edit($id = null)
{
if (!$id && empty($this->data))
{
$this->Session->setFlash(__('Invalid User', true));
$this->redirect(array('action'=>'index'));
}
if (!empty($this->data))
{
if ($this->User->save($this->data))
{
$this->Session->setFlash(__('The User has been saved', true));
$this->redirect(array('action'=>'index'));
}
else
{
$this->Session->setFlash(__('The User could not be saved. Please, try again.', true));
}
}
if (empty($this->data))
{
$this->data = $this->User->read(null, $id);
}
}
function delete($id = null)
{
if (!$id)
{
$this->Session->setFlash(__('Invalid id for User', true));
$this->redirect(array('action'=>'index'));
}
if ($this->User->del($id))
{
$this->Session->setFlash(__('User deleted', true));
$this->redirect(array('action'=>'index'));
}
}
}
Here is the test:
/* SVN FILE: $Id$ */
/* UsersController Test cases generated on: 2009-08-05 17:08:03 : 1249507923*/
App::import('Controller', 'Users');
class TestUsers extends UsersController
{
var $autoRender = false;
var $redirectUrl;
var $redirectStatus;
var $renderedAction;
var $renderedLayout;
var $renderedFile;
var $stopped;
function redirect($url, $status = null, $exit = true)
{
$this->redirectUrl = $url;
$this->redirectStatus = $status;
}
function render($action = null, $layout = null, $file = null)
{
$this->renderedAction = $action;
$this->renderedLayout = (is_null($layout) ? $this->layout : $layout);
$this->renderedFile = $file;
}
function _stop($status = 0)
{
$this->stopped = $status;
}
}
class UsersControllerTest extends CakeTestCase
{
var $fixtures = array('user');
var $Users = null;
function startTest()
{
$this->Users = new TestUsers();
$this->Users->constructClasses();
$this->Users->Component->initialize($this->Users);
}
function prepareForAction()
{
$this->Users->beforeFilter();
$this->Users->Component->startup($this->Users);
}
function endTest()
{
$this->Users->Session->destroy();
unset($this->Users);
ClassRegistry::flush();
}
//-----------------------------------------------------------------------
function testUsersControllerInstance()
{
$this->assertTrue(is_a($this->Users, 'UsersController'));
}
function testLogin()
{
$this->Users->data = array(
'User' => array(
'username' => 'admin',
'password' => 'admin'
)
);
$this->prepareForAction();
$this->Users->login();
$this->assertNotNull($this->Users->redirectUrl);
$this->assertEqual($this->Users->Session->read('Auth.User.id'), 1);
}
}
The test you have isn't really testing your UsersContoller, you're really testing the AuthComponent. If you want to do this you need to make sure you setup your TestUsersController the same as it would be in your app. In the case of your testLogin you need to set the controller's action and url:
function testLogin()
{
$this->Users->data = array(
'User' => array(
'username' => 'admin',
'password' => 'admin'
)
);
$this->Users->params['url']['url'] = '/users/login';
$this->Users->params['action'] = 'login';
$this->prepareForAction();
$this->Users->login();
$this->assertNotNull($this->Users->redirectUrl);
$this->assertEqual($this->Users->Session->read('Auth.User.id'), 1);
}
Alternately, I would suggest taking another look at Mark's mock objects post and using those methods to write tests for the controller code and mocking the auth component.

Categories