Pass value from my view to my model - mysql

i want to pass a value from my view to my model. i want to pass the $plate value to my model to get all the data that will match the $plate. here is my code:
View
<a href="<?=base_url()?>services/view_services?plate=<?php echo $plate; ?>">
<button type="button" class="btn btn-primary">View Services</button>
Controller
public function view_services()
{
$data['results'] = $this->Services_model->fetch_car_services($config['per_page'], $page);
$this->load->view('car_services', $data);
}
Model
public function fetch_car_services($plate)
{
$this->db->where('car_plate_number =', $plate);
$this->db->order_by('created_datetime', 'DESC');
$query = $this->db->get('service_jobs');
$result = $query->result();
$this->db->save_queries = false;
return $result;
}
it doesn't seem to work. Thanks in advance.

You have to get the variable somehow, using your method:
//services/view_services?plate=someplate
public function view_services() {
$plate = $this->input->get('plate');
if (is_null($plate)) {
// error!
}
$data['results'] = $this->Services_model->fetch_car_services($plate);
$this->load->view('car_services', $data);
}
a better way of doing things:
//services/view_services/someplate
public function view_services($plate = null) {
if (is_null($plate)) {
// error!
}
$data['results'] = $this->Services_model->fetch_car_services($plate);
$this->load->view('car_services', $data);
}
Please check for errors! I already did half the work for you here, you just have to figure out how you want to handle them. This also includes checking if num_rows > 0 in your model or count($data['results']) > 0 in your controller and sending an error if that is the case. Your foreach in your view will fail if you don't.

View :
Controller:
public function view_services($plate)
{
$data['results'] = $this->Services_model->fetch_car_services($config['per_page'], $page);
$this->load->view('car_services', $data);
}

Related

How to send values from variables and arrays from controller to the model

I want to change the script below.
where the script below is using the query "like" and "array" to find data.
I want to send these 2 variables to the model and send them back to the controller for processing.
My Controller:
if($lewati == 0){
$sql = "SELECT * FROM tb_fotografer WHERE spesifikasi_foto LIKE '%$kata[$i]%'";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)){
// $jml_id_filter = count($id_filter);
// $id_filter[$jml_id_filter] = $row['id'];
$filter_ok++;
}
}
My Model:
function tampil_data_spesifik($kata,$i)
{
return $this->db->query('select tb_fotografer WHERE spesifikasi_foto LIKE '%$kata[$i]%'');
}
From codeigniter's official documentation, it's a better practice to do all db queries in your model and you don't need to manually type any database connection scripts.
Your controller handles incoming requests, often times from routes. For codeigniter version 3, your controller method should be
public function method(){
$lewati = 0;
$array_data = array(3, 5, 9, 4);
$another_thing = $array_data[1] //get first item
if($lewati === 0){
$result = $this->model_name->method_in_model($lewati, $another_thing); //your model will accept two params
}
echo json_encode($result);
}
Then you can update your model to something like this
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_name extends CI_Model {
public function method_in_model($lewati, $another_thing){
$this->db->where('column_name', $lewati);
$this->db->like('spesifikasi_foto LIKE', $another_thing);
$result = $this->db->get('YOUR_TABLE_NAME');
if(empty($result->row_array())){
return true;
}else{
return false;
}
}
}
Let me know if it solved your problem already
in your controller method
$this->load->model('name_of_the_model_class');
$data = $this->name_of_the_model->function_name($variable1,$variable2);
in your model class method
//do whatever your process and return the output
return $output;

Check if db row has specific values

I am creating an event, each event will have attendees, I got this working fine, the problem I am having is an attendee can attend the same event twice, which is not good.
Event View
<?php if($this->session->userdata('user_id')): ?>
<hr>
<?php echo form_open('/attendees/add/'.$event['id']); ?>
<input type="hidden" name="user_id" value="<?php echo $_SESSION['user_id']; ?>">
<input type="submit" value="I'm in!" class="btn btn-success">
</form>
<?php endif; ?>
Attendees Controller
<?php
class Attendees extends CI_Controller {
public function add($event_id) {
// Check login
if(!$this->session->userdata('logged_in')){
redirect('users/login');
}
$this->form_validation->set_rules('user_id', 'required|callback_check_userid_eventid');
if($this->form_validation->run() === FALSE){
$this->session->set_flashdata('attendee_not_added', 'You are already on the list.');
redirect('home');
} else {
$this->attendee_model->add_attendee($event_id);
// Set message
$this->session->set_flashdata('attendee_added', 'You have been added to this event.');
redirect('events');
}
}
}
Attendees Model
<?php
class Attendee_model extends CI_Model {
public function __contruct() {
}
public function get_attendees($id = FALSE){
if($id === FALSE) {
$query = $this->db->get('attendees');
return $query->result_array();
}
$this->db->select('attendees.id, attendees.team, attendees.is_goalie, event.id, user.first_name, user.last_name');
$this->db->from('attendees');
$this->db->join('event', 'attendees.event_id = event.id', 'inner');
$this->db->join('user', 'attendees.user_id = user.id', 'inner');
$this->db->where('event.id', $id);
$query = $this->db->get();
return $query->row_array();
}
public function add_attendee($event_id){
$data = array(
'event_id' => $event_id,
'user_id' => $this->session->userdata('user_id')
);
return $this->db->insert('attendees', $data);
}
// Check attendee exists in event
public function check_userid_eventid($event_id, $user_id){
$query = $this->db->get_where('attendees', array('user_id' => $user_id, 'event_id' => $event_id));
if(empty($query->row_array())){
return true;
} else {
return false;
}
}
}
As you can see I tried creating a custom callback on the button form validation but it did not work.
If anyone can point me in the right direction, let me know if I am even somewhat close.
Thanks in advance.
You are not passing the $event_id value to the callback function. Replace your validation with the following line
$this->form_validation->set_rules('user_id', 'User ID', 'required|callback_check_userid_eventid['.$event_id.']');
add following callback function inside the Attendees Controller file
public function check_userid_eventid($user_id, $event_id){
$CI =& get_instance();
$CI->load->database();
$CI->form_validation->set_message('user_id_unique', "Sorry, that %s is already being used.");
return isset($CI->db) ? ($CI->db->limit(1)->get_where('attendees',compact('user_id','event_id'))->num_rows() == 0) : false;
}
Your callback is in a model that form validation knows nothing about. If you look at the docs: callbacks should be in the same controller as the form validation method that uses it.
However, you can use a function in a model as a callback with a different syntax:
$this->form_validation->set_rules(
'username', 'Username',
array(
'required',
array($this->users_model, 'valid_username')
)
);
as documented here.
Finally, on a false return, you need to make sure that you are setting a message as seen in this example:
public function username_check($str)
{
if ($str == 'test')
{
$this->form_validation->set_message('username_check', 'The {field} field can not be the word "test"');
return FALSE;
}
else
{
return TRUE;
}
}
In conclusion: the documentation has all the answers.
Put the call back function into Controller
<?php
class Attendees extends CI_Controller {
public function add($event_id) {
// Check login
if(!$this->session->userdata('logged_in')){
redirect('users/login');
}
$this->form_validation->set_rules('user_id', 'required|callback_check_userid_eventid');
if($this->form_validation->run() === FALSE){
$this->session->set_flashdata('attendee_not_added', 'You are already on the list.');
redirect('home');
} else {
$this->attendee_model->add_attendee($event_id);
// Set message
$this->session->set_flashdata('attendee_added', 'You have been added to this event.');
redirect('events');
}
}
// Check attendee exists in event
public function check_userid_eventid($event_id, $user_id){
$query = $this->db->get_where('attendees', array('user_id' => $user_id, 'event_id' => $event_id));
if(empty($query->row_array())){
return true;
} else {
return false;
}
}
}

how do i make session variables available through out all controllers and views in cakephp 3.2

my login function in users controller
public function login() {
if ($this->request->is('post')) {
$user = $this->Auth->identify();
// print_r($user);
// die();
if ($user['role'] === 'student') {
$this->Auth->setUser($user);
$session = $this->request->session();
$session->write('user', $user);
return $this->redirect(['controller' => 'Useracountinfo/addinfo']);
} elseif .....
and my add info function in the Useracountinfo
public function addinfo()
{
$this->loadModel('Users');
$userinfo= $this->Users->find('all');
$session = $this->request->session();
$userinfo = $session->read('user');
//print_r($userinfo);
//die();
$this->set($userinfo);
$user = $this->Useracountinfo->newEntity();
if ($this->request->is('post')) {
$user = $this->Useracountinfo->patchEntity($userinfo, $this->request->data);
print_r($user);
die();
if ($this->Useracountinfo->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
$this->set(compact('useracountinfo'));
$this->set('_serialize', ['useracountinfo']);
}`
and in my view i have something like this
<?php echo '<strong>'.$userinfo['email'].'</strong>'; ?>
the correct syntax is (see the manual)
$this->set('variable_name', somevalue);
so in your case
$this->set('userinfo', $userinfo);
mind that this is not a session variable but just a php variable that cake share from the controller to the view
if you want this to be available in every view you can do it in AppController
but you don't even need to do that because $this->request->session() is already always available in views too
This said I don't fully understand what you are trying to achieve so maybe there are better solutions

Error in updating data in code igniter model

this is model function
<?php
class change_data extends CI_Model {
function __construct() {
parent::__construct();
}
function change($id,$action)
{
if($action==0)
$st=1;
else
$st=0;
$data = array('gud_status' => $st);
$where = "id=".$id;
$this->db->update_string('gallery', $data, $where);
return $this->db->affected_rows();
}
}
everything is working fine.. also getting 2 parameter values but table updation fails.. affect 0 rows!!!
any body can sort this!!
Pass where condition in array. Ex-
function change($id,$action)
{
if($action==0)
$st=1;
else
$st=0;
$data = array('gud_status' => $st);
$where = array('id'=>$id);
$this->db->update_string('gallery', $data, $where);
return $this->db->affected_rows();
}

How to force convert json action in Cakephp Rest

i need force convert json action in cakephp rest response. When i set '_serialize' like this
$this->set(array('message' => $lessons, '_serialize' => array('message')));
it works but some turkish characters view in unicode like "\u00e7al\u0131\u015fma alan\u0131".
It's solution is render data with json_encode($data, JSON_UNESCAPED_UNICODE) but cakephp render it automatically. How to force json_encode with JSON_UNESCAPED_UNICODE ?
Sorry for bad English.
in cakePHP 3 you can say in controller:
$this->set('_jsonOptions', JSON_UNESCAPED_UNICODE);
$this->set('_serialize', ['zones']);
which will override the options used.
JsonView doesn't accept options
There's no way to inject options in the json_encode() call invoked by JsonView, as it's hard coded optionless in the _serialize() method like this:
protected function _serialize($serialize) {
// ...
if (version_compare(PHP_VERSION, '5.4.0', '>=') && Configure::read('debug')) {
return json_encode($data, JSON_PRETTY_PRINT);
}
return json_encode($data);
}
Use a custom/extended view
So if you want to use automatic serialization, then you have to create your own/an extended view that either accepts options, or hard codes your desired options.
Here's an (untested) example with hard coded options. The _serialize() method is basically just a copy with the JSON_UNESCAPED_UNICODE option added:
App::uses('JsonView', 'View');
class MyJsonView extends JsonView {
protected function _serialize($serialize) {
if (is_array($serialize)) {
$data = array();
foreach ($serialize as $alias => $key) {
if (is_numeric($alias)) {
$alias = $key;
}
if (array_key_exists($key, $this->viewVars)) {
$data[$alias] = $this->viewVars[$key];
}
}
$data = !empty($data) ? $data : null;
} else {
$data = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null;
}
if (version_compare(PHP_VERSION, '5.4.0', '>=') && Configure::read('debug')) {
return json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}
return json_encode($data, JSON_UNESCAPED_UNICODE);
}
}
See also http://book.cakephp.org/2.0/en/views.html#creating-your-own-view-classes
I haven't tested this myself, so it's just from the top of my head.
You could write your own View class extending JsonView and override the _serialize method.
https://github.com/cakephp/cakephp/blob/4e8e266754a25748f481b2f567e45f767808be53/lib/Cake/View/JsonView.php#L131
<?php
App::uses('JsonView', 'View');
class MyCustomView extends JsonView {
protected function _serialize($serialize) {
if (is_array($serialize)) {
$data = array();
foreach ($serialize as $alias => $key) {
if (is_numeric($alias)) {
$alias = $key;
}
if (array_key_exists($key, $this->viewVars)) {
$data[$alias] = $this->viewVars[$key];
}
}
$data = !empty($data) ? $data : null;
} else {
$data = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null;
}
return json_encode($data, JSON_UNESCAPED_UNICODE);
}
}
And then in your controller do something like
<?php
App::uses('MyCustomView', 'View');
class SomeController extends AppController {
public function someMethod() {
$this->viewClass = 'MyCustomView';
// What ever you normally do
}
}