how to create insert function in model - php

In controller I am sending data like that :
$data=array[
'table'=>'ci',
'where'=>'',
'val'=>['name'=>$name,
'pass'=>$pass,
'mobile'=>$mobile,
'date'=>$date,
'status'=>$status
]
];
$this->load->model('show_model');
$this->show_model->insert_data($data);
In the model code I have:
<?php
class show_model extends CI_model{
public function insert_data($data){
}
}
?>
I want to create a function to data in ci table what is the method to get the data from the controller and how can i make the funcyion for insert for what i am sending the data.

I think you are trying to perform insert operation but you couldn't figure it out. Lets take it step by step. Codeigniter has a database library which comes with installation. You can load that library in config->autoload.php and provide database credentials in config->database.php. All set!
Once you have loaded database library you can use bunch of database function. E.g
For Insertion
$this->db->insert('table_name',data);
// Your data can be array of the data you want to insert
Let's say you want to send data from your controller to your Model to save it to db you can do something like this
Class Controller_Name extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('your_model');
}
public function index() {
$data=array(
'username' => 'Your Name',
'email' => 'Your Email',
'password' => 'Your Password'
);
// Send it to DB
$this->your_model->save_data($data);
// Show success
echo 'Data Saved';
}
}
Now in your Model you will have the function save data like this
Class Your_model extends CI_Model {
public function __construct(){
parent::__construct();
}
public function save_data($data){
// Assuming the table name is users
$this->db->insert('users',$data);
}
}
You can do a lot of modifications and enhancements, there is a lot of learning ahead but this is a fair start.

Try
public function insert($data) {
if($this->db->insert('table_name', $data)) {
//Success
}
}
Ensure you are connected to your database from database.php in application/config folder
Hope it helps

Related

How to access one controller action inside another controller action?

I am using cakephp-2.x. I have one function name user_info() in the UsersController.php i want to access this in another controller name MessagesController.php
Code -
UsersController.php
public function user_info(){
$user_id=$this->Session->read('Auth.User.id');
$data=$this->User->findById($user_id);
$this->set('user_info',$data);
}
MessagesController.php
public function index(){
//$userInfo=new UsersController();
//$userInfo->user_info();
$this->user_info();
pr($data);
}
Error Message-
Fatal Error
Error: Call to undefined method MessagesController::user_info()
File: E:\xampp\htdocs\2014\myshowcam\msc\app\Controller\MessagesController.php
Line: 18
Notice: If you want to customize this error message, create app\View\Errors\fatal_error.ctp
Typically if you're trying to access a function in one controller from another controller you have a fundamental flaw in your project's logic.
But in general object usage is thus:
$otherController = new whateverMyControllerNameIs();
$otherController->functionName();
However I'm not familiar enough with cake to tell you the pitfalls of doing such a thing. For example I have no idea what this would do to routes or what other variables/objects are required to initialize a controller correctly.
EDIT:
Ref: CakePHP 2.3.8: Calling Another Controller function in CronController.php
App::import('Controller', 'Products'); // mention at top
// Instantiation // mention within cron function
$Products = new ProductsController;
// Call a method from
$Products->ControllerFunction();
Try requestAction function of cakephp
$result = $this->requestAction(array('controller' => 'users', 'action' => 'user_info'));
Why would a simple, When can complicated?
All the information for a registered user of User model is accessible in the following manner:
AppController.php
public $user_info; /* global scope */
public function beforeFilter(){
$this->user_info = $this->Auth->user(); // for access user data in any controller
$this->set('user_info_view',$this->Auth->user()); // for access user data in any view or layout
}
MessagesController.php
public function index(){
debug($this->user_info);
$my_messages = $this->Message->find('all',
array('conditions' => array('Message.user_id' => $this->user_info['id']))
}
....
layout or view.ctp
<?php echo $user_info_view['name']; ?> // email, etc
Why not take advantage of the way CakePHP handles relationships? There's a very easy way to achieve what you're trying to do without extending controllers or loading in additional controllers which seems excessive for your example.
Inside AppController's beforeFilter()
Configure::write('UserId', $this->Session->read('Auth.User.id'));
This will allow you to access the UserID from your models
Inside your User's model, create the following function
/**
* Sample query which can be expanded upon, adding fields or contains.
*
* #return array The user data if found
*/
public function findByUserId() {
$user = $this->find('first', array(
'conditions' => array(
'User.id' => Configure::read('UserId')
)
));
return $user;
}
Inside your Users controller (Minimal is better, no?)
public function user_info() {
$this->set('user', $this->User->findByUserId());
}
Inside your Messages controller
public function index() {
$this->set('user', $this->Message->User->findByUserId());
// --- Some more stuff here ---
}
And that's it, no need to be extending controllers, just make sure your Message and User model are related to each other, failing that you can bindModel or use ClassRegistry::init('User')-> for example.

Yii - Get data from Model

I have the following in my controller:
public function actionIndex() {
$userID = Yii::app()->user->getId();
$arNotifs = Notification::model()->getNotificationsByUserId($userID);
$this->render('index', array("arNotifications"=>$arNotifs, "userID"=>$userID));
}
I have the following in a file called notification.php in my models:
class Notification extends CActiveRecord {
// ------ BUNCH OF STUFF
public function getNotificationsByUserId($userId) {
$userId = (int) $userId;
$query = Yii::app()->db->createCommand();
$query->select('n.id, n.title, n.content, n.updated');
$query->from('hr4_notification_x_user nxu');
$query->join('hr4_notification n', 'nxu.notification = n.id');
$query->where('nxu.user=:userId', array(':userId' => $userId);
return $query->queryAll();
}
// ------ MORE STUFF
}
When I rem out the line
$arNotifs = Notification::model()->getNotificationsByUserId($userID);
and replace it with a static value it works fine. It seems that in my noob ways I am missing some vital step. The controller seems to have no idea what Notification is.
Thanks in advance
I believe the most elegant way to get your notifications on the controller would be something like:
$arNotifs = Yii::app()->user->model->notifications;
To achieve such, you might need to implement a getModel() method on your class that extends CWebUser. That method would return an instance of an user that extends CActiveRecord. Then your user model can have a relations() method, like the following:
class UserModel extends CActiveRecord {
public function relations() {
return array(
'notifications' => array(self::HAS_MANY, 'Notification', 'user'),
);
}
}
This will prevent you from writing that query and will make things more clear (on both, models and controller). If you will, read a bit about relations.
You cannot use the Notification model like this.
You can instantiate it with $notification = new Notification();
and then do a $notification->getNotificationsByUserId($userID);
However this would be not very good. I would move the notification code from the model to the User model.
This was you dont even need to pass the user ID.
Or maybe even better, if you make a component out of Notification and use it as a service.

Code Igniter RESTful Modeling and Controller

I have been developing using non framework for about 3 years and I have heard about PHP framework codeigniter.
I think I missed something using this framework which is used for API for my mobile application.
I've facing some problem to get data from database using Phil's CI framework, RESTful plugin. My browser shows error code:
{"status":false,"error":"Unknown method."}
Using my logic below:
controller: user.php
<?php
require(APPPATH.'libraries/REST_Controller.php');
class User extends REST_Controller{
public function user_get()
{
//IF USER NOT EXIST
if(!$this->get('id'))
{
$this->response(NULL, 400);
}
//CHECK TO MODEL FUNCTION
$user = $this->user_model->get_user($this->get('id'));
//IF USER EXIST
if($user)
{
$this->response($user, 200); // 200 being the HTTP response code
}
}
public function user_put()
{
// create a new user and respond with a status/errors
}
public function user_post()
{
// update an existing user and respond with a status/errors
}
public function user_delete()
{
// delete a user and respond with a status/errors
}
}
?>
model: user_model.php
<?php
class User_model extends CI_Model{
function __construct() {
parent::__construct();
}
function get_user($id){
$query = $this->db->get('mt_user', array('idmt_user'=>$id));
return $query->row_array();
}
}
?>
i'm accessing the database which is has this rows:
idmt_user,username,password, emails, createdate
accessed using mozilla:
#http://localhost/<project>/index.php/user/<userid>
Where's the error(s) ?
thanks.
update,
i am already defined the autoloads for database. But this problem still persist. Is there any helps? thanks
as stated below in answer, i tried to access the url, /user/get_user/ but still showing the same result. Is there any problem using idmt_user in database?
Insert in controllers:
function __construct() {
parent::__construct();
$this->load->model('user_model');
}
And try this route:
http://localhost//index.php/user/user/id/
I believe that the url you are accessing with is wrong.. Try accessing with the url #http://localhost/<project>/index.php/user/<method_name>/<user_id>
Another way of doing it would be using the URI Class.
Instead of writing the following:
//IF USER NOT EXIST
if(!$this->get('id'))
{
$this->response(NULL, 400);
}
Changed to:
$userid = $this->uri->segment(3);
Would be 3 based off the url being http://localhost/<project>/user/<method_name>/<user_id>
Reference for URI Class: http://www.codeigniter.com/user_guide/libraries/uri.html
In order to use $this->get(); there would have to be a query parameter to get. Example: id=
If you are passing query parameters than you could store these values in a array as shown below.
if(!empty($this->get()))
{
$params[] = $this->get();
}
I hope this helps.
You should to try include your model file into your controller file by using a __construct() function, like this:
function __construct(){
parent::__construct();
$this->load->model(array('user_model'));
}

Cannot get DataMapper to work in CodeIgniter

I'm trying to implement an ORM in a CodeIgniter application, but cannot get it to work. To start I'm just trying to instantiate a simple test model:
<?php
class Cart extends DataMapper
{
public function __construct()
{
// model constructor
parent::__construct();
}
var $validation = array(
'username' => array(
'label' => 'UserName',
'rules' => array('required', 'trim', 'unique', 'alpha_dash', 'min_length' => 1, 'max_length' => 50),
)
);
}
?>
And then in the Controller I try this:
public function __construct()
{
parent::__construct();
$this->load->model('cart');
}
public function index()
{
$cart = new Cart();
}
But I don't even get past the constructor. The debugger stops and gives me a message saying "Waiting for an incoming connection with ide key xxxxx" (random number)
BTW the cart model class file name is in lower case, but the class name in upper case. I tried both in the constructor.
I have followed the instructions for installation carefully, copying the two datamapper files to libraries and config folders, as well as autoloading the datamapper library.
But it just doesn't work. Am I missing something? The table I'm trying to map is only a test table that actually only has an id and a username field. I don't actually understand the validation array, but just followed the examples in the docs and modified to my field. The id field doesn't seem like anyone has put in the validation array.
I should also mention that I'm a newbie at CodeIgniter.
Your code seems mostly correct for use with DataMapper ORM and CodeIgniter.
To explain things a bit, DataMapper is just an abstraction layer. It handles a lot of the necessities when working with databases and mapping your objects to your tables. That being said, you don't have to load your models, etc. As long as you are autoloading your database library and datamapper library, you can use DataMapper.
The validation array lets DataMapper know the requirements to your properties. So, if you try to save an object and one of the properties that you've created/changed doesn't meet those requirements, then your save will fail and you'll get an error message:
// For example
if ($myObj->save())
{
// $myObj validation passed and is saved to db
}
else
{
// $myObj validation failed, save did not complete
echo $myObj->error->string;
}
Codeigniter already has a library named Cart, so you wouldn't want to name your model Cart. So you could rename that model to Basket or something else that makes sense.
I know you're still just trying to get things to work, but I feel you need to think about your data structure a bit. You wouldn't save the username in the Cart object, that's why we use relations. So, I would structure it a bit like this:
// baskets table (a table represents many baskets, therefore it is plural)
id
user_id
blah
blah
created
updated
// users table
id
username
email_address
created
updated
// basket model (a model represents 1 basket, therefore it is singular)
class Basket extends DataMapper
{
public function __construct()
{
parent::__construct();
}
var $has_one = array('user'); // each basket belongs to one user
var $validation = array(...);
}
// user model
class User extends DataMapper
{
public function __construct()
{
parent::__construct();
}
var $has_many = array('basket'); // each user can have many baskets
var $validation = array(...);
}
// controller
public function __construct()
{
parent::__construct();
}
public function index()
{
$basket = new Basket();
$basket->blah = 'whatever';
$basket->save();
// at this point, $basket is saved to the database
// now let's add it to the user
$user = new User();
$user->where('id', 1)->get(1);
// now we have a user
// save the relationship to the basket
$user->save($basket);
// now $basket->user_id == 1
// get the username from the basket
$u = $basket->user->get();
$username = $u->username;
// yes, there are faster and shorter ways to write most of this,
// but I think for beginners, this syntax is easier to understand
}
The CodeIgniter documentation about models states that you can load a model by calling
$this->load->model('Model_name');
in the constructor, and that you can access this model in your controller by doing
$this->Model_name->function();
So you should change your Controller code into
public function __construct()
{
parent::__construct();
$this->load->model('Cart');
}
public function index()
{
$this->Cart->functionCall();
}

codeigniter show (my)sql insert warnings

I have this controller and model:
class MyModel extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function insert($data_array)
{
$this->db->insert('table', $data_array);
if($this->db->affected_rows() == 1) {
return true;
}
return false;
}
}
class Panel extends CI_Controller
{
public function submitPrimer()
{
// evaluate data
$this->load->library('form_validation');
$this->load->model('MyModel', 'mymodel');
// validate, set_rules....
$data = array(
'column1' => $value1;
// .....
);
if($this->mymodel->insert($data)) {
echo "inserted";
}
}
}
Is there any kind of $this->db->show_warnings() in CI. In mysql console there is 'show warnings' command which says for example if you have datatype: float and you insert like this: insert into table (attribute_float) values(''). The proper way would be insert into table (attribute_float) values(NULL).
I also am wondering if 'insert' should go to models. I always assumed only 'select/get' data would go.
As much as I'm aware, and from user guide, I don't think that Codeigniter has such a function, for such validation use form_validation library, it's pretty good.
As for insert/edit/delete, they usually go to the model, but it depends on you.

Categories