I want to change the database, but my coding deletes all its contents.
I use codeigneter 3
my controller:
public function update_() {
$id = $this->input->post('id');
$nama = $this->input->post('nama');
$alamat = $this->input->post('alamat');
$number = $this->input->post('number');
$rekening = $this->input->post('rekening');
$email = $this->input->post('email');
$data = array(
'nama' => $nama,
'alamat' => $alamat,
'number' => $number,
'rekening' => $rekening,
'email' => $email,
);
$where = array (
'id' => $id
);
$this->Modellaptop->update_client($where, $data, 'tb_invoice ');
$this->session->set_flashdata('message',
'<div class="alert alert-success" role="alert">Update success </div>'
);
redirect('Admin/invoice');
}
my model:
public function update_client($where,$data,$table)
{
$this->db->where($where);
$this->db->update($table, $data);
}
maybe you can try like this
in controller
public function update_() {
$id = $this->input->post('id');
$nama = $this->input->post('nama');
$alamat = $this->input->post('alamat');
$number = $this->input->post('number');
$rekening = $this->input->post('rekening');
$email = $this->input->post('email');
$data = [
'nama' => $nama,
'alamat' => $alamat,
'number' => $number,
'rekening' => $rekening,
'email' => $email
];
$where = array (
'id' => $id
);
$this->Modellaptop->update_client($where, $data);
$this->session->set_flashdata('message',
'<div class="alert alert-success" role="alert">Update success </div>'
);
redirect('Admin/invoice');
}
in model
public function update_client($where,$data = [])
{
$this->db->where($where);
$this->db->update('tb_invoice(your table name)', $data);
//dont forget to return
return $this->db->affected_rows();
}
Related
I currently use Laravel 8 and I want to know how do I ignore unique validation when a user is updating their profile? If the user is updating every field except the pageName I don't want it to throw a vaildation error cause the user is already the owner of that pageName. I tried this code but it gives error: ErrorException
Undefined variable: user
$request->validate([
'image' => 'nullable|mimes:jpeg,jpg,png|max:100',
'pageName' => 'nullable|alpha_dash|unique:users,littlelink_name'.$user->id,
'pageColor' => 'nullable',
'pageFontcolor' => 'nullable',
'pageDescription' => 'nullable|regex:/^[\w.\- ]+$/i',
'pagePixiv' => 'nullable|url',
]);
This is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Auth;
use DB;
use App\Models\User;
use App\Models\Button;
use App\Models\Link;
class UserController extends Controller
{
//Statistics of the number of clicks and links
public function index()
{
$userId = Auth::user()->id;
$littlelink_name = Auth::user()->littlelink_name;
$links = Link::where('user_id', $userId)->select('link')->count();
$clicks = Link::where('user_id', $userId)->sum('click_number');
return view('studio/index', ['littlelink_name' => $littlelink_name, 'links' => $links, 'clicks' => $clicks]);
}
//Show littlelink page. example => http://127.0.0.1:8000/+admin
public function littlelink(request $request)
{
$littlelink_name = $request->littlelink;
$id = User::select('id')->where('littlelink_name', $littlelink_name)->value('id');
if (empty($id)) {
return abort(404);
}
$information = User::select('littlelink_name', 'littlelink_color', 'littlelink_fontcolor', 'littlelink_pixiv', 'littlelink_description')->where('id', $id)->get();
$links = DB::table('links')->join('buttons', 'buttons.id', '=', 'links.button_id')->select('links.link', 'links.id', 'buttons.name')->where('user_id', $id)->orderBy('up_link', 'asc')->get();
return view('littlelink', ['information' => $information, 'links' => $links, 'littlelink_name' => $littlelink_name]);
}
//Show buttons for add link
public function showButtons()
{
$data['buttons'] = Button::select('name')->get();
return view('studio/add-link', $data);
}
//Save add link
public function addLink(request $request)
{
$request->validate([
'link' => 'required|url',
'button' => 'required'
]);
$link = $request->link;
$button = $request->button;
$userId = Auth::user()->id;
$buttonId = Button::select('id')->where('name' , $button)->value('id');
$links = new Link;
$links->link = $link;
$links->user_id = $userId;
$links->button_id = $buttonId;
$links->save();
return back()->with('message', 'Link Added');
}
//Count the number of clicks and redirect to link
public function clickNumber(request $request)
{
$link = $request->link;
$linkId = $request->id;
if(empty($link && $linkId))
{
return abort(404);
}
Link::where('id', $linkId)->increment('click_number', 1);
return redirect()->away($link);
}
//Show link, click number, up link in links page
public function showLinks()
{
$userId = Auth::user()->id;
$data['links'] = Link::select('id', 'link', 'click_number', 'up_link')->where('user_id', $userId)->orderBy('created_at', 'desc')->paginate(10);
return view('studio/links', $data);
}
//Delete link
public function deleteLink(request $request)
{
$linkId = $request->id;
Link::where('id', $linkId)->delete();
return back();
}
//Raise link on the littlelink page
public function upLink(request $request)
{
$linkId = $request->id;
$upLink = $request->up;
if($upLink == 'yes'){
$up = 'no';
}elseif($upLink == 'no'){
$up = 'yes';
}
Link::where('id', $linkId)->update(['up_link' => $up]);
return back();
}
//Show link to edit
public function showLink(request $request)
{
$linkId = $request->id;
$link = Link::where('id', $linkId)->value('link');
$buttons = Button::select('name')->get();
return view('studio/edit-link', ['buttons' => $buttons, 'link' => $link, 'id' => $linkId]);
}
//Save edit link
public function editLink(request $request)
{
$request->validate([
'link' => 'required|url',
'button' => 'required',
]);
$link = $request->link;
$button = $request->button;
$linkId = $request->id;
$buttonId = Button::select('id')->where('name' , $button)->value('id');
Link::where('id', $linkId)->update(['link' => $link, 'button_id' => $buttonId]);
return redirect('/studio/links');
}
//Show littlelinke page for edit
public function showPage(request $request)
{
$userId = Auth::user()->id;
$data['pages'] = User::where('id', $userId)->select('littlelink_name', 'littlelink_color', 'littlelink_fontcolor', 'littlelink_pixiv', 'littlelink_description')->get();
return view('/studio/page', $data);
}
//Save littlelink page (name, description, logo)
public function editPage(request $request)
{
$request->validate([
'image' => 'nullable|mimes:jpeg,jpg,png|max:100',
'pageName' => 'nullable|alpha_dash|unique:users,littlelink_name'.$user->id,
'pageColor' => 'nullable',
'pageFontcolor' => 'nullable',
'pageDescription' => 'nullable|regex:/^[\w.\- ]+$/i',
'pagePixiv' => 'nullable|url',
]);
$userId = Auth::user()->id;
$littlelink_name = Auth::user()->littlelink_name;
$profilePhoto = $request->file('image');
$pageName = $request->pageName;
$pageColor = $request->pageColor;
$pageFontcolor = $request->pageFontcolor;
$pageDescription = $request->pageDescription;
$pagePixiv = $request->pagePixiv;
User::where('id', $userId)->update(['littlelink_name' => $pageName, 'littlelink_color' => $pageColor, 'littlelink_fontcolor' => $pageFontcolor, 'littlelink_pixiv' => $pagePixiv, 'littlelink_description' => $pageDescription]);
if(!empty($profilePhoto)){
$profilePhoto->move(public_path('/img'), $littlelink_name . ".png");
}
return back()->with('message', 'Saved');
}
//Show user (name, email, password)
public function showProfile()
{
$userId = Auth::user()->id;
$data['profile'] = User::where('id', $userId)->select('name', 'email')->get();
return view('/studio/profile', $data);
}
//Save user (name, email, password)
public function editProfile(request $request)
{
$request->validate([
'name' => 'required|unique:users',
'email' => 'required|email|unique:users',
'password' => 'required|min:8',
]);
$userId = Auth::user()->id;
$name = $request->name;
$email = $request->email;
$password = Hash::make($request->password);
User::where('id', $userId)->update(['name' => $name, 'email' => $email, 'password' => $password]);
return back();
}
}
Anyone know how to fix this?
You can change your code to the following
$userId = Auth::user()->id;
$request->validate([
'image' => 'nullable|mimes:jpeg,jpg,png|max:100',
'pageName' => 'nullable|alpha_dash|unique:users,littlelink_name,'.$userId,
'pageColor' => 'nullable',
'pageFontcolor' => 'nullable',
'pageDescription' => 'nullable|regex:/^[\w.\- ]+$/i',
'pagePixiv' => 'nullable|url',
]);
you can use the Rule object to make that validation:
'pageName' => ['nullable','alpha_dash', Rule::unique('users','littlelink_name')->ignore($user->id)
hello Everyone i am new in codeigniter i was try to insert data in database but not work properly.but not insert data in database.I was activate helper and auto load is i was write.
my controller
public function save() {
if($this->input->post('submit')) {
$this->Checkout_model->process();
}
}
my model
function process() {
$name = $this->input->post('name');
$phone = $this->input->post('phone');
$email = $this->input->post('email');
$address = $this->input->post('address');
$data=array (
'name' => $name,
'phone' => $phone,
'email' => $email,
'address' => $address
);
$this->db->insert('customers',$data);
}
Use this code In Controller
public function save() {
if($this->input->post('submit')) {
$name = $this->input->post('name');
$phone = $this->input->post('phone');
$email = $this->input->post('email');
$address = $this->input->post('address');
$data=array (
'name' => $name,
'phone' => $phone,
'email' => $email,
'address' => $address
);
$this->Checkout_model->process($data);
}
}
In Model
function process($data) {
$this->db->insert('customers',$data);
}
I want to create keys based on the information provided by the User. For eg If user insert his name,phone,country,some other information then my code should concatenate some fields and store a unique key into the same user table where i have field key. I hope you understand my issue.I am new to codeigniter and have used the base model by Joost Van.
The Controller Code:
<?php
class Reseller extends Admin_Controller
{
public function __construct ()
{
parent::__construct();
}
public function index ()
{
// Fetch all users
$this->data['users'] = $this->reseller_m->get();
// Load view
$this->data['subview'] = 'admin/reseller/index';
$this->load->view('admin/_layout_main', $this->data);
}
public function reseller ()
{
// Fetch all users
$this->data['users'] = $this->reseller_m->get();
// Load view
$this->data['subview'] = 'admin/reseller/users'; //Users variable stores the suvbview
$this->load->view('admin/_layout_main', $this->data);
}
public function edit ($id = NULL)
{
// Fetch a user or set a new one
if ($id) {
$this->data['user'] = $this->reseller_m->get($id);
count($this->data['user']) || $this->data['errors'][] = 'User could not be found';
}
else {
$this->data['user'] = $this->reseller_m->get_new();
}
// Set up the form
$rules = $this->reseller_m->rules_admin;
$id || $rules['password']['rules'] .= '|required';
$this->form_validation->set_rules($rules);
// Process the form
if ($this->form_validation->run() == TRUE) {
$data = $this->reseller_m->array_from_post(array('sip_username','sip_password','key','allocation_block','name','email','password','phone','balance','user_num','address','country','created','modified','status'));
$data['password'] = $this->reseller_m->hash($data['password']);
$key=$this->reseller_m->save($data, $id);
for($i=1; $i<=$data['user_num'];$i++)
{
$userdata=array('key'=>$key);
// here users is taken name of user table with retailer_id is field
$this->db->insert('users',$userdata);
}
redirect('admin/reseller');
}
// Load the view
$this->data['subview'] = 'admin/reseller/edit';
$this->load->view('admin/_layout_main', $this->data);
}
public function delete ($id)
{
$this->reseller_m->delete($id);
redirect('admin/reseller');
}
}
The Model:
<?php
class Reseller_M extends MY_Model {
protected $_table_name = 'reseller';
protected $_order_by = 'name';
protected $_timestamps = TRUE;
public $rules = array(
'email' => array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email|xss_clean'
),
'password' => array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required'
),
);
public $rules_admin = array(
'name' => array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|xss_clean'
),
'email' => array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email|callback__unique_email|xss_clean'
),
'password' => array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|matches[password_confirm]'
),
'password_confirm' => array(
'field' => 'password_confirm',
'label' => 'Confirm password',
'rules' => 'trim|matches[password]'
),
'sip_username' => array(
'field' => 'sip_username',
'label' => 'Sip Username',
'rules' => 'trim|required|'
),
'sip_password' => array(
'field' => 'sip_password',
'label' => 'SIP Password',
'rules' => 'trim|required|'
),
);
function __construct ()
{
parent::__construct();
}
public function get_new(){
$user = new stdClass();
// $user->id = '';
$user->sip_username='';
$user->sip_password='';
$user->key='';
$user->allocation_block='';
$user->name='';
$user->email = '';
$user->password = '';
$user->phone='';
$user->user_num='';
$user->address = '';
$user->status = '';
$user->country='';
$user->created = '';
$user->modified = '';
$user->balance = '';
return $user;
$this->session->set_userdata($data);
}
public function get_user_profile(){
$this->db->select('id,sip_password,sip_username,phone,key,address,country,created,modified,user_num,allocation_block,status,email, name, balance');
$query = $this->db->get_where('reseller', array('id' => $this->session->userdata('id')));
return $query->result();
}
function insert_item($key)
{
$this->reseller = $key;
$this->db->set($this->reseller, $this);
}
public function hash ($string)
{
return hash('sha512', $string . config_item('encryption_key'));
}
public function loggedin ()
{
return (bool) $this->session->userdata('loggedin');
}
}
The Base Model Where CURD Functions are defined
<?php
class MY_Model extends CI_Model {
protected $_table_name = '';
protected $_primary_key = 'id';
protected $_primary_filter = 'intval';
protected $_order_by = '';
public $rules = array();
protected $_timestamps = FALSE;
function __construct() {
parent::__construct();
}
public function array_from_post($fields){
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
public function get($id = NULL, $single = FALSE){
if ($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
}
elseif($single == TRUE) {
$method = 'row';
}
else {
$method = 'result';
}
return $this->db->get($this->_table_name)->$method();
}
public function get_by($where, $single = FALSE){
$this->db->where($where);
return $this->get(NULL, $single);
}
public function save($data, $id = NULL){
// Set timestamps
if ($this->_timestamps == TRUE) {
$now = date('Y-m-d H:i:s');
$id || $data['created'] = $now;
$data['modified'] = $now;
}
// Insert
if ($id === NULL) {
!isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
$this->db->set($data);
$this->db->insert($this->_table_name);
$id = $this->db->insert_id();
}
// Update
else {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->set($data);
$this->db->where($this->_primary_key, $id);
$this->db->update($this->_table_name);
}
return $id;
}
public function delete($id){
$filter = $this->_primary_filter;
$id = $filter($id);
if (!$id) {
return FALSE;
}
$this->db->where($this->_primary_key, $id);
$this->db->limit(1);
$this->db->delete($this->_table_name);
}
}
I am a begineer in yii. I am making a basic structure - an employee. I am uploading their images and saving image name in database and also showing it on my view page. But I want to change the image name to employee id.
For Ex:
desert.jpg changes to 01.jpg or any other employee id.
Please help me.
CONTROLLER:
public function actioncreate(){
$dept_list = department_mod::model()->dept_list();
$data['dept_list'] = CHtml::listData($dept_list,'value', 'text');
$team_list = team_mod::model()->team_list();
$data['team_list'] = CHtml::listData($team_list,'value', 'text');
$des_list = employee_mod::model()->des_list();
$data['des_list'] = CHtml::listData($des_list,'value', 'text');
$report_to_list = report_to_mod::model()->report_to_list();
$data['report_to_list'] = CHtml::listData($report_to_list,'value', 'text');
$model_upload = new upload_mod;
$data['model_upload'] = $model_upload;
$this->render('create',$data);
}
public function actionsave(){
$q = Employee_mod::model()->data_save($_POST);
$data = $_POST;
$exp = 'profile';
$emp_upload_path = 'assests/images/';
$p = $emp_upload_path;
echo $p;
if (!is_dir($p)) {
mkdir($p,0777);
}
$path = $p.$exp.'/';
if (!is_dir($path)) {
mkdir($path,0777);
}
$model_upload = new upload_mod;
$file_name = "";
$model_upload->upload_file = CUploadedFile::getInstance($model_upload,'userfile');
if($model_upload->validate()) {
$model_upload->upload_file->saveAs($path . $model_upload->upload_file);
$file_name = $model_upload->upload_file;
}else{
var_dump($model_upload->getErrors());
}
$data['file_name'] = $file_name;
$q = Employee_mod::model()->imagesave($q , $file_name);
$this->redirect(array('employee/list'));
MODEL:
function data_save($data)
{
$input = array(
'first_name' => $data['first_name'],
'middle_name' => $data['middle_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'cnic' => $data['cnic'],
'dob' => $data['dob'],
'department' => $data['dept_id'],
'location' => $data['location'],
'created_by' => 'admin',
'team' => $data['id'],
'des' => $data['des_id'],
'report_to' => $data['id'],
'joining_date' => $data['joining_date'],
);
$q = Yii::app()->db->createCommand();
$q->insert('emp',$input);
$insert_id = Yii::app()->db->getLastInsertID();
return $insert_id;
}
function imagesave($empno , $file_name)
{
$file = array(
'image' => $file_name
);
$q = Yii::app()->db->createCommand();
$q->update('emp', $file, 'empno=' . $empno);
}
function imageeditsave($empno , $file_name)
{
$file = array(
'image' => $file_name
);
$q = Yii::app()->db->createCommand();
$q->update('emp', $file, 'empno=' . $empno);
}
function data_editsave($data,$emp_no)
{
$input = array(
'first_name' => $data['first_name'],
'middle_name' => $data['middle_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'cnic' => $data['cnic'],
'dob' => $data['dob'],
'department' => $data['dept_id'],
'location' => $data['location'],
'created_by' => $data['created_by'],
'team' => $data['id'],
'des' => $data['des_id'],
'report_to' => $data['id'],
'joining_date' => $data['joining_date'],
);
$q = Yii::app()->db->createCommand();
$q-> update('emp',$input,'empno =' . $emp_no);
$insert_id = Yii::app()->db->getLastInsertID();
return $insert_id;
}
The problem is here:
$q = Yii::app()->db->createCommand();
$q->update('emp', $file, 'empno=' . $empno);
update is an ActiveRecord method and you are using it with createCommand! You need to change that code to this:
Employee_mod::model()->updateByPk($empno, array('image' => $file_name));
Is there a way that I can update a form input using something like insert_id?
I have a form for adding factories to a table and I use the insert_id to store the factories id in another table too after submit.
this all works great, but is there such a way for $this->db->update?
My model for updating:
function updatebedrijf($id, $data)
{
$this->db->where('idbedrijven', $id);
$this->db->update('bedrijven', $data);
}
My controller function for updating:
function updatebedrijven()
{
$dbres = $this->db->get('categorieen');
$ddmenu = array();
foreach ($dbres->result_array() as $tablerow) {
$ddmenu[$tablerow['idcategorieen']] = $tablerow['Categorie'];
}
$data['opties'] = $ddmenu;
$data['info'] = $this->members_model->getbedrijf($id);
$data['id'] = $this->uri->segment(3);
$this->load->view('members/header');
$this->load->view('members/editform', $data);
$this->load->view('members/footer');
}
for adding factories i use this with insert_id:
controller:
function addbedrijven()
{
$this->members_model->addbedrijf();
redirect('members/index');
}
model:
function addbedrijf()
{
$data1 = array(
'Bedrijfsnaam' => $this->input->post('Bedrijfsnaam'),
'Postcode' => $this->input->post('Postcode'),
'Plaats' => $this->input->post('Plaats'),
'Telefoonnummer' => $this->input->post('Telefoonnummer'),
'Email' => $this->input->post('Email'),
'Website' => $this->input->post('Website'),
'Profiel' => $this->input->post('Profiel'),
'Adres' => $this->input->post('Adres'),
'logo' => $this->input->post('logo')
);
$this->db->insert('bedrijven',$data1);
if($this->db->affected_rows() >= 1)
{
$to_bedrijfcategorieen['idbedrijven'] = $this->db->insert_id();
$to_bedrijfcategorieen['idcategorieen'] = $this->input->post('categorieen');
$this->insert_bedrijfcat($to_bedrijfcategorieen);
}else{
return FALSE;
}
}
function insert_bedrijfcat($data1)
{
$this->db->insert('bedrijfcategorieen', $data1);
return $this->db->affected_rows() >= 1 ? TRUE : FALSE;
}
Hope it's clear enough.