Deleting database rows using cakephp - cakephp

I'm currently making a newsletter that let users subscribe and unsubscribe. Subscribing is a success but not on unsubscribing. can you help me out guys, here's my codes...
Controller
class AddsController extends AppController {
public $helpers = array('Html','Form','Session','Flash');
public $components=array('Session');
public function index() {
if($this->request->is('post')) //posting to db
{
$this->Add->create();
$this->Add->save($this->request->data);
$this->Flash->set('The user has been saved.', array('element' => 'success'));
return $this->redirect('index'); //redirects to index.ctp
}
}
/*public function delete($email = null) {
if($this->request->is('post')) {
$this->Add->exists($email) {
$this->Add->delete($email);
$this->Session->Flash('Unsubscribed');
return $this->redirect('index');
}
}
function delete(){ //delete html
$email = $this->request->data['email'];
if($this->Add->exists($email)){
$this->Add->delete($email);
$this->Session->Flash('Unsubscribed');
//$this->Flash->set('Unsubscribed', array('element' => 'danger'));
return $this->redirect('index');
}
} */
function delete() {
$email = $this->request->data['email'];
if($this->Add->exists($email)){
$this->Add->delete($email);
$this->Session->Flash('Unsubscribed');
//$this->Flash->set('Unsubscribed', array('element' => 'danger'));
return $this->redirect('index');
}
}
}
View
<?php echo "<section>";
echo $this->Form->create('Add'); //<form > 'modelname'
echo "<label>E-mail:</label>";
echo $this->Form->input('email',array('label'=>false , 'placeholder'=>'your email')); //email input
echo $this->Form->submit('Subscribe'); //subscrib button
echo $this->Form->end();//</form>
echo "</section>";
echo "<section>";
echo $this->Form->delete('Add',array('action'=>'delete')); //<form >
echo "<label>E-mail:</label>";
echo $this->Form->input('email',array('label'=>false , 'placeholder'=>'your email')); //email input
echo $this->Form->submit('Unsubscribe',array('action'=>'index'),array('style'=>'background:red'));
echo $this->Form->end();//</form>
echo "</section>";
My view is just "entering data into db and deleting existed data out the db
Model
<?php
App::uses('AppModel' , 'Model');
class Add extends AppModel
{
public $name = "Add";
public $useTable = 'request';
public $primaryket = 'id';
public $useDbConfig = 'default';
}
db tablename: request; Just the delete row
Thank you in advance!!!

try to use below method (pass unique id of user) hope it will work:
$user = $this-> Add->findByEmail($email);
$this-> Add->delete($user['User']['id'], false);

Alternative way
$userId = $this->User->field('id', array('User.email' => $email));
if($userId) {
$this->User->id = $userId;
$this->User->delete();
$this->log('User of '.$email.' record deleted successfully');
} else {
$this->log('There is no record present of particular email = '. $email);
}

Related

How to encrypt a password in cakephp 2.x version

Hello everyone i am using cakephp 2.x, as i am new to here, i need to encrypt my password before it stores to database
User.ctp : I am posting like this to post
<?php
echo $this->Form->input('password',array('type'=>'password','label'=>false,'div'=>false,'class'=>'form-control','id'=>'password'));
?>
Controller:
public function setting()
{
$this->layout='setting_template';
if($this->Session->read('username')==""){
$this->redirect(array('action' => 'user_login'));
}
elseif ($this->Session->read('username') == "admin" )
{
if($this->request->is('post'))
{
$this->data['password'] = encrypt($this->data ['password']);
if ($this->Login->save($this->request->data)) {
$this->Session->setFlash('The user has been saved');
$this->redirect(array('action' => 'setting'));
} else {
$this->Session->setFlash('The user could not be saved. Please, try again.');
}
}
$opp=$this->Login->find('all');
$this->set('login',$opp);
}
else{
echo "<script type='text/javascript'> alert('Permission Denied'); </script>";
$this->redirect(array('action' => 'index'));
}
}
Login controller:
public function login()
{
$this->layout='login_template';
if($this->data)
{
$this->Session->write('id',$this->data['Login']['id'] );
$results = $this->Login->find('first',array('conditions' => array('Login.password' => $this->data['Login']['password'],'Login.username' => $this->data['Login']['username'])));
$this->Session->write('name',$results['Login']['name']);
if ($results['Login']['id'])
{
$this->Session->write($this->data['Login']['username'].','. $this->data['Login']['password']);
$this->Session->write('username',$this->data['Login']['username']);
$this->redirect(array('action'=>'index'));
}
else
{
$this->Session->setFlash("error");
}
}
How can i encrypt the password file and also how can use the Model
As you are using CakePhp go with framework's best practices.
When creating new user records you can hash a password in the
beforeSave callback of your model using appropriate password hasher
class:
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class User extends AppModel {
public function beforeSave($options = array()) {
if (!empty($this->data[$this->alias]['password'])) {
$passwordHasher = new SimplePasswordHasher(array('hashType' => 'sha256'));
$this->data[$this->alias]['password'] = $passwordHasher->hash(
$this->data[$this->alias]['password']
);
}
return true;
}
}
You don’t need to hash passwords before calling $this->Auth->login(). The various authentication objects will hash passwords individually.
If you are using different model than User for authentication you need to define that in AppController. In your Case you need to do something like this in AppController:
$this->Auth->authenticate = array(
'Form' => array('userModel' => 'Login')
);
If you wish to hash your password, try this:
$hashedPassword = AuthComponent::password('original_password');
See Here :Cakephp Password Hashing.

Unsupported operand types on CakePHP

I have a this
**Fatal_Error:
Error: Unsupported operand types
File: C:\wamp\www\newsletter\lib\Cake\View\Helper\FlashHelper.php
Line: 90**
every time I clicked the submit button. here's my code..
**AddsController.php //Controller**
<?php
class AddsController extends AppController {
public $helpers = array('Html','Form','Session');
public $components=array('Session');
public function index() {
if($this->request->is('post'))
{
$this->Add->create();
$this->Add->save($this->request->data);
$this->Session->setFlash('Success');
return $this->redirect(array('action'=>'index'));
}
}
}
?>
**Add.php //Model/**
<?php
App::uses('AppModel' , 'Model');
class Add extends AppModel
{
public $name = "Add";
public $useTable = 'request';
public $primaryket = 'id';
public $useDbConfig = 'default';
}
?>
**index.ctp //View/Adds/index.ctp**
<?php
echo $this->Form->create('add');
echo $this->Form->input('email');
echo $this->Form->submit('submit');
echo $this->Form->end();
?>
dbname: exercise; table: request;
goal: all inputted data must be in the db.
Thank you in advance!
Use FlashHelper to set yor flash messages, not Session->flash
https://book.cakephp.org/2.0/en/core-libraries/helpers/flash.html
// In your Controller
public $helpers = array('Html','Form','Session','Flash');
$this->Flash->set('The user has been saved.', array(
'element' => 'success'
));

save() function in cakephp save null values

My problem is that i dont know save() function of cakephp insert null values in posts table !
When I try to add a post: http://i.stack.imgur.com/fhRVn.png
After redirecting the inserted data is null: http://i.stack.imgur.com/YstBb.png
My PostsController.php is:
App::uses('AppController', 'Controller');
class PostsController extends AppController{
public $components = array('Session');
public $helpers = array('Html', 'Form');
public function index() {
$this -> set('posts', $this->Post->find('all'));
}
public function view($id = null){
if(!$id){
throw new NotFoundException(_('il faut choisir un post'));
}
$post=$this->Post->findById($id);
if(!$post){
throw new NotFoundException(_('invalide Post !'));
}
$this->set('post',$post);
} // fin de "view"
public function add(){
if($this->request->is('post'))
{
$this->Post->create();
if ($this->Post->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.'));
}
//debug($this->Post->validate);
}//fin d'ajout
} // fin de "appcontroller"
My Post.php model file is:
class Post extends appModel {
//public $name='Post';
public $validate = array(
'title' => array('rule' => 'notEmpty'),
'body' => array('rule' => 'notEmpty')
);
}
My view form post is:
echo $this->Form->create('post');
echo $this->Form->input('title');
echo $this->Form->input('body',array('rows' => '3'));
echo $this->Form->end('Ajouter');
in your view maybe your problem that you Model is Post not post
echo $this->Form->create('Post');
echo $this->Form->input('title');
echo $this->Form->input('body',array('rows' => '3'));
echo $this->Form->end('Ajouter');

which method of model to update the row in cakephp

i have trouble in creating method in controller of cakephp to update the my existing row in a table, can anyone suggest me appropriate model method to update the row in table
<?php
class UsersController extends AppController
{
public function update($id)
{
if(isset($_REQUEST['update']))
{
// method of model to update the row
}
else
$this->set('user',$this->User->find('first',array('conditions'=>array('id'=>$id))));
}
}
?>
http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-save-array-data-null-boolean-validate-true-array-fieldlist-array
$this->User->id = $id;
$this->User->save($this->request->data);
Try the code.......
<?php
class UsersController extends AppController {
public function update($id = null) {
if ($id) {
if ($this->request->is('post')) {
$this->User->id = $id;
$this->User->save($this->request->data);
} else {
$this->set('user', $this->User->find('first', array('conditions' => array('id' => $id))));
}
}
}
}
?>
#burzum after reading the tutorial which link provide by you i found the solution to the my problem, in model updateAll() method available in model by using this i have update row of the table.
public function update($id)
{
if(isset($_REQUEST['update']))
{
$this->User->id=$id;
if($this->User->updateAll(array('User.fname'=>"'".$_REQUEST['fname']."'",'User.lname'=>"'".$_REQUEST['lname']."'",'User.email'=>"'".$_REQUEST['email']."'"),array('id'=>$id)))
echo '<script>alert("update successfully")</script>';
else
echo '<script>alert("failes to update ")</script>';
}
else
$this->set('user',$this->User->find('first',array('conditions'=>array('id'=>$id))));
}

CakePHP save() doesn't save data

I don't see anything wrong with my code. But it does not save data:
<?php
class ProductsController extends AppController{
var $name = 'Products';
//var $helpers = array('Form');
//var $scaffold;
function index(){
$this->Product->recursive = 1;
$products = $this->Product->find('all');
$this->set('products',$products);
//pr($products);
}
function add(){
$categories = $this->Product->Category->find('list',array(
'field'=>array('Category.categoryName')
));
$this->set('categories',$categories);
if(!empty($this->data)){
if($this->Product->save($this->data)){
$this->Session->setFlash('Saved');
}
}
}
}
?>
it flashes "Saved" but nothing is being inserted in my table. What could possibly be wrong when it should be functioning properly. :(
Below is my add.ctp model:
<h2>ADD</h2>
<?php echo $this->Form->create('Product',array('action'=>'add')); ?>
<?php
echo $form->input('ProductName');
echo $form->input('categories');
echo $form->end('DONE');
?>
You have to use the create() method before to save
function add(){
$categories = $this->Product->Category->find('list',array(
'field'=>array('Category.categoryName')
));
$this->set('categories',$categories);
if(!empty($this->data)){
$this->Product->create();
if($this->Product->save($this->data)){
$this->Session->setFlash('Saved');
}
}
}

Resources