I have an update function in my Model which I call from My controller as
if($_POST)
{
$this->User_model->update('user_about',$_POST,$this->session->userdata['id']);
}
takes three parameters, table name, post data and user id. The function is defined in the Model as
public function update($table,$data,$id)
{
$row=$this->db->select('*')->from($table)->WHERE('user_id',$id)->row();
if($row)
{
$this->db->WHERE('user_id',$id)->UPDATE($table,$data);
}
else
{
$data['user_id']=$id;
$this->db->insert($table,$data);
}
}
What I am doing here is checking if the record of particular user doesn't exist it should insert, otherwise update. Works like a charm
Question
Is there a way to skip the IF condition block?. Is there any provision in query builder which performs the check itself?
Here is a custom generic insert and update on duplicate function that I always used in my programming.
public function updateOnDuplicate($table, $data )
{
if (empty($table) || empty($data)) return false;
$duplicate_data = array();
foreach($data AS $key => $value) {
$duplicate_data[] = sprintf("%s='%s'", $key, $value);
}
$sql = sprintf("%s ON DUPLICATE KEY UPDATE %s", $this->db->insert_string($table, $data), implode(',', $duplicate_data));
$this->db->query($sql);
return $this->db->insert_id();
}
You can use the above function in the model and call it in the controller. The function will update the value if the duplicate occurs. Check out following blog post if you need detail explanation A Generic CodeIgniter Function for both Update and Insert.
Related
Simply i have a two table
GALLARIES AND MEDIA
In a GALLARIES table id,title,venueId i have saved gallary folder name for the particular venue.
In MEDIA Table I have id,imagepath,is_thumb(0 or 1),gallery_Id
What i want to do is when i set is_thumb_image(1) then i have call two function
1 st for unset image all with gallery_id and after i call second function for set is_thumb_image for particular image.
Is it possible to call one function only and perform both functionalty.
Here is my Controller code.
$albumId = $request->album_id; //table galleries id - album name
if($request->is_thumb_image == "true") {
$media1->UnsetThumbImage($albumId); // first unset thumb_image
$media->setThumbImage($media->id); // call for set thumb_image
} else {
$request->is_banner_image = false;
}
Here is my model functions
public function setThumbImage($mediaId) {
try {
DB::table('media')
->where('id', $mediaId)
->update(['is_thumb_image' => 1]);
$this->is_thumb_image = 1;
} catch (\Exception $ex) {
echo $ex->getMessage();
dd($ex->getTraceAsString());
}
}
public function UnsetThumbImage($albumid) {
DB::table('media')
->where('gallery_id', $albumid)
->update(['is_thumb_image' => 0]);
$this->is_thumb_image = 1;
}
How can i do it calling only one function.
You can use CASE with MySQL to update on various conditions. You'd need to use a raw query to do this with Laravel I believe.
Something like:
UPDATE media
SET is_thumb_image = CASE
WHEN id = $mediaId THEN 1
WHEN gallery_id = $albumId THEN 0
END
For that you need to:
specify which column is it gonna be. But best practice is to do this in different methods, as they have different jobs, and column action.
$this->setThumbImage('id', $id);
$this->setThumbImage('gallery_id', $id);
Pass what you need to according to your requirement.
public function setThumbImage($id, $field) {
DB::table('media')
->where("$field", $id)
->update(['is_thumb_image' => 0]);
$this->is_thumb_image = 1;
}
I am fairly new to CodeIgniter and I'm sure there's a simple answer. I need to determine if there are records returned prior to executing this line of code in my VIEW:
foreach ($announcements->result_array() as $announcement_data){
My disconnect is that I can't check if array is empty because it is not an array yet until the foreach line is executed. Checking if $announcements is empty also doesn't work.
CONTROLLER:
public function summary() {
$this->load->model('Propinfo_model');
$data['propid'] = "516";
$data['propinfo'] = $this->Propinfo_model->get_propinfo($data['propid']);
// query for proposal info
$data['announcements'] = $this->Propinfo_model->get_announcements($data['propid']);
$this->load->view('summary_view', $data);
}
MODEL:
// Select all records from 'prop_announcements' table per prop ID
public function get_announcements($propid) {
// Build query
$this->db->select('*');
$this->db->from('prop_announcements P');
$this->db->join('ssp_users', 'P.user = ssp_users.userid');
$this->db->where('P.propid', $propid);
return $this->db->get();
}
VIEW:
foreach ($announcements->result_array() as $announcement_data){
echo $announcement_data['user']; // example field
}
You use
if ($announcements->num_rows() == 0) {
//code for no rows
}
https://www.codeigniter.com/userguide3/database/results.html
How to insert same data into database after update in ORM?
For example i have function save() and inside this function i have update and it's working, but i don't know how to make insert with old update data. I mean it should make something like history in database. I only hope you can understand what i mean. Thanks for help.
public function save(Validation $validation = NULL)
{
if ($this->loaded()) {
// UPDATE TRIGGER
DB::update($this->_table_name)
->set(array('ud_status' => 'D'))
->where('ud_status', '=', 'A')
->where('ud_uId', '=', $this->ud_uId)
->execute($this->_db);
return false;
} else {
// INSERT TRIGGER
return parent::save($validation);
}
}
$query = DB::insert('users', array('username', 'password'))->values(array('fred', 'p#5sW0Rd'));
https://kohanaframework.org/3.3/guide/database/query/builder#insert
I am trying to get the value of a row in the database but not working out that well. I not sure if can work like this.
I am just trying to get the value but also make sure it from the group config and the key.
Model
function getTitle() {
return $this->db->get('setting', array(
->where('group' => 'config'),
->where('key' => 'config_meta_title'),
->where('value'=> ) // Want to be able to return any thing in the value
))->row();
}
In the controller I would do this:
function index() {
$data['title'] = $this->document->getTitle();
$this->load->view('sample', $data);
}
First, you have this line set to this:
$data['title'] $this->document->getTitle();
That should be an = assignment for $this->document->getTitle(); like this:
$data['title'] = $this->document->getTitle();
But then in your function you should actually return the setting value from your query with row()->setting:
function getTitle() {
return $this->db->get('setting', array(
->where('group' => 'config'),
->where('key' => 'config_meta_title'),
->where('value'=> ) // Should return this row information but can not.
))->row()->setting;
}
But that said, I am unclear about this:
->where('value'=> ) // Should return this row information but can not.
A WHERE condition is not a SELECT. It is a condition connected to a SELECT that allows you to SELECT certain values WHERE a criteria is met. So that should be set to something, but not really sure what since your code doesn’t provide much details.
Found Solution Working Now. For Getting Single Item From Database In Codeigniter
Loading In Library
function getTitle($value) {
$this->CI->db->select($value);
$this->CI->db->where("group","config");
$this->CI->db->where("key","config_meta_title");
$query = $this->CI->db->get('setting');
return $query->row()->$value;
}
Or Loading In Model
function getTitle($value) {
$this->db->select($value);
$this->db->where("group","config");
$this->db->where("key","config_meta_title");
$query = $this->db->get('setting');
return $query->row()->$value;
}
Okay, so I have this snippet of code in a controller. However, it's all DB driven and should really be in model - I get that. However, as you can see in the IF statement, I need to pass along $data to my view. Based on the outcome. I tried pasting this chuck of coding in a method in my model (calling the model method via controller), however the $data[update_prompt] string is not getting called by the view...
How would I translate this code into a model - sending the $data values back to my controller to embed in my view?
// show appropriate upgrade message if user has free account
$id = $this->session->userdata('user_id');
$this->db->select('subscription'); // select the subscription column
$this->db->where('id', $id); //find id in table that matches session id
$query = $this->db->get("subscriptions"); // connect to this database
$subscribe = $query->result_array(); //returns the result of the above
if($subscribe[0]['subscription'] == 'freebie') // if subscription column equals 'freebie' in the $subscribe array, do this:
{
$data['update_prompt'] = $this -> load -> view('shared/upgrade_subscription', '', TRUE); // adds view within view, $update_prompt
}
else
{
$data['update_prompt'] = '';
}
You would add a function in your model, like so:
public function myModelFunction($id) {
//we return row as we are looking up by primary key and are guaranteed only one row
return $this->db->select('subscription')
->where('id', $id)
->get('subscriptions')
->row();
}
Then, in your controller:
public function myControllerFunction() {
$subscribe = $this->my_model->myModelFunction($this->session->userdata('id'));
if($subscribe->subscription == 'freebie') // if subscription column equals 'freebie' in the $subscribe array, do this:
{
$data['update_prompt'] = $this -> load -> view('shared/upgrade_subscription', '', TRUE); // adds view within view, $update_prompt
}
else
{
$data['update_prompt'] = '';
}
}