updating a field in DB table using Codeigniter - php

I have two tables one is 'student' another is 'status'.The student table has a foreign key status_status_id. I want to update this status_status_field. In my view the all the status (junior, senior, fresher, sophomore) from the status are shown in a drop down menu.
I want to update the status_status_id (initially it has the value 0) field of student table by taking inputs from this drop down. And to update i also need the id of a particular student. The problem is the field status_status_id is not updating. The following error is showing-
A Database Error Occurred
Error Number: 1054
Unknown column 'Array' in 'where clause'
UPDATE `student` SET `0` = '' WHERE `id` = Array
Filename: Z:\www\CI\system\database\DB_driver.php
Line Number: 330
my controller
function update(){
$id=$this->input->post('id');
$data=array(
'status_status_id'=>$this->input->post('status_status_id'),
);
$this->status_model->update($data, $id);
}
}
my model
function update($data,$id){
$this->db->where('id', $id);
$this->db->update('student', $data);
}
}
View for adding a status
<?php echo form_open('status_controller/update');
$r=$info[0]->id;
$data=array (
'id'=>$r,
'status_status_id'=>set_value('status_status_id')
);
?>
<p><?php echo form_input($data); ?>
<p><select name ='status_status_id'>
<?php echo form_error('status_status_id'); ?>
<br /><?php
$getType = mysql_query("SELECT status_id, status FROM status ORDER BY status_id");
while($type = mysql_fetch_object($getType)){
echo "<option value=\"{$type->status_id}\">{$type->status} </option>",set_value('status_status_id');
} ?></p><p><?php echo form_submit( 'submit', 'Update Status'); ?></p><?php echo form_close(); ?>

I see the view having few errors. I'll just rewrite it with comments, it should then work.
Notice that you should move all database queries outside the view, and of course add validation. I am not sure if ID is actually an integer.
// I suppose this gives us a single ID, not an array of IDs or something else
$r = $info[0]->id;
// put the ID in a hidden field, so POST sends an "id" variable
$hidden_fields = array('id' => $r);
// add the hidden fields directly in form_open()
echo form_open('status_controller/update', '', $hidden_fields);
// making $getType = mysql_query("SELECT status_id, status FROM status ORDER BY status_id"); in an active record way
$this->db->select('status_id, status');
$this->db->order_by('status_id', 'asc');
$query = $this->db->get('status');
// loop to make an array of the statuses to insert in form_dropdown() array('value' => 'display')
$statuses = array();
foreach ($query->result() as $row)
{
$statuses[$row->status_id] = $row->status;
}
// you would probably be able to get the current status_status_id
// I will suppose that $info[0]->status_status_id holds that data
echo form_dropdown('status_status_id', $statuses, set_value('status_status_id', $info[0]->status_status_id));
echo form_error('status_status_id');
echo form_submit( 'submit', 'Update Status');
echo form_close();
The controller:
function update(){
// again, this is suspicious from your example, check if it's not an Array
$id = $this->input->post('id');
$data = array(
'status_status_id' => $this->input->post('status_status_id'),
);
$this->status_model->update($data, $id);
}
The model:
function update($data, $id){
$this->db->where('id', $id);
$this->db->update('student', $data);
}

Related

codeigniter Check if data exist in database update table row

How to check if a column exists in query builder Codeigniter 3?
my database table name is "tags" and this table have two column (post_id and tag) here is my code to add tags to post:
//add post tags
public function add_post_tags($post_id)
{
//tags
$tags = trim($this->input->post('tags', true));
$tags_array = explode(",", $tags);
if (!empty($tags_array)) {
foreach ($tags_array as $tag) {
$tag = trim($tag);
if (strlen($tag) > 1) {
$data = array(
'post_id' => $post_id,
'tag' => trim($tag),
'tag_slug' => str_slug(trim($tag))
);
if (empty($data["tag_slug"]) || $data["tag_slug"] == "-") {
$data["tag_slug"] = "tag-" . uniqid();
}
//insert tag
$this->db->insert('tags', $data);
}
}
}
}
I want to check if data exists in the database update the post_id column if not exist insert new data
"post_id" column like "5,8,9"
I want to add the post number to the previous numbers when I update "post_id" column
for example after update "post_id" column This table is like this "5,8,9,11" here 11 is my last post id
Try using replace() instead :
$this->db->replace('tags', $data);
Basically it inserts a new record if it doesn't exist, it updates it according to its primary or unique key if it does exist.

yii1 update DB query giving error

I want to update one field in my db. I have the below query, but I am getting error in this.
$list = Test::model()->find(array(
'select'=>'name',
'condition'=>'id=:id AND name=:name AND provider="fb"',
'params'=>array(
':id'=>Yii::app()->user->id,
':name'=> $name,
),
));
$list->name = $user_name[$k]['name'];
if($list->save())
{
echo "done";exit;
}
else
{
$error = $list->getErrors();
var_dump($error);exit;
}
Error:
'Column name must be either a string or an array
This happens when you don't have a primary key in your table and you try to save some data in table. check if you have set primary key and it set properly. more details

Insert multiple values of input fields one column in rows in Codeigniter

I have a form which contains some input fields and checkboxes, I want to insert all the values of input in one column (rows).
Here is my form:
<form action="" method="post">
<label>Built in year</label>
<input name="feature[]">
<label>View</label>
<input name="feature[]">
here is my controller:
function create_listing(){
$this->load->view('form');
if($_POST){
$feature = array ( 'feature' => $_POST['feature'] );
foreach($feature as $fkey => $fvalue ){
$this->Mdata->f_detail($fvalue);
}
}
and here is my model:
function f_detail($fvalue){
$this->db->insert('feature',$fvalue);
return $this->db->insert_id();
}
I am getting an error :
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '0, 1, 2) VALUES ('build in year', 'view', 'parking space')' at line 1
INSERT INTO `feature` (0, 1, 2) VALUES ('build in year', 'view', 'parking space')
What's wrong in my code. Anyone please tell me .
Regards
Use $this->input->post() instead of $_POST() in codeigniter both are equivalent.
Controller:
function create_listing(){
if($this->input->post()){
$feature = $this->input->post('feature');
foreach($feature as $fkey => $fvalue ){
$ids []= $this->Mdata->f_detail($fvalue);//$Ids is array of returned id
}
$this->load->view('form');//load view after database operations
}
Model:
In your model you need to specify column name like below:
function f_detail($fvalue)
{
$this->db->insert('feature',array('column_name'=>$fvalue));//specify column name
return $this->db->insert_id();
}
You can input multiple value into one column with implode function.
Controller:
function create_listing(){
if($this->input->post()){
$data = array (
'feature' => implode(",", $this->input->post('feature'))
);
$this->Mdata->f_detail($data);
}
else{
$data = array ();
$this->load->view('form', $data);
}
}
Model:
function f_detail($data){
$this->db->insert('feature',$data);
return $this->db->insert_id();
}

How to update/insert array of values to database using Yii2 ( many values for one id that repeats )

I am collecting some data from database and then display it in index view. There I have check box near every row, so I can allow users to pick their favorites.
Picture and text is selected from one table cpv. That table has fields: id, title, image. Since logged in user can pick up to 3 of the entries as favorites, I am having table to store relation between user and cpv.id he chose. user_cpv table has columns: id, user_id, cpv_id.
I made some dirty way of displaying data + checkboxes, and I made some way of passing information ( cpv.id ) to the actionUpdate that should save cpv.id's. But I can not figure out how to save all of this to user_cpv table. Can someone give me some idea about how to do this properly and how to do validation that user can not select more than 3 boxes? Here is my code:
index view :
<?php foreach ($values as $data): ?>
<tr>
<td>Img goes here</td>
<td>Title goes here</td>
<?php // here I have some dirty code, for each row displayed I am executing query that should find entry in
// user_cpv table where cpv_id there is == with the cpv.id taken drom cpv table.
// can this be done more efficient ?
?>
<?php $cpv = UserCpv::getCpvByCpvId($data['cpvId']) ?>
<?php if ($cpv): ?>
<td><?= Html::checkbox('favorite[]', true, ['value' => $data['cpvId']]) ?></td>
<?php else: ?>
<td><?= Html::checkbox('favorite[]', false, ['value' => $data['cpvId']]) ?></td>
<?php endif ?>
</tr>
<?php endforeach ?>
Form is opened with Html::form:
My actionUpdate:
public function actionUpdate()
{
$userId = Yii::$app->user->identity->id;
// array of checked cpv.ids (['0' => someId, ['1' => otherCheckedId]])
$favorites = Yii::$app->request->post('favorite');
$model = UserCpv::findOne(['user_id' => $userId]);
if ($model)
{
// this does not work
$update = UserCpv::updateAll(['cpv_id' => $favorites], "user_id = $userId");
return $this->render('index', [
'model' => $model
]);
}
else
{
# code...
}
// ???
}
Do anyone have any idea how this should be done properly ?
I see two ways: first one is to create 'batchUpdate' method - but it will not be the same for different database types. So I will describe second one, as it seems to be pretty simple.
1. Remove all user relations:
UserCpv::deleteAll(['user_id' => $userId]);
2. Create array for batchInsert method:
$data = [];
foreach($favorites as $cpv_id) {
$data[] = ['cpv_id' => $cpv_id, 'user_id' => $userId];
}
3. Batch insert your data
Yii::$app->db->createCommand()->batchInsert(
UserCpv::tableName(),
['cpv_id', 'user_id'],
$data
)->execute();

CodeIgniter Getting the result of a query as a text input value

I wrote a small piece to get a value from a database table according to the input user provides. Quickly here are the events:
User inputs number to an input and submit form
That data are supposed to call the controller, and then the controller have to match and grab relevant data from the database table, and pass it to the controller again.
Then the controller must pass it to the view, where another text input (readonly) picks up the data as the value.
But what I received was an error:
Message: Undefined variable: due_amount
Filename: main/new_payment.php
Line Number: 148
Line number 148 in new_payment.php is
);
in the View.
This is my Model:
function get_by_room_number($room_data) {
$this->db->select('due_amount');
$query = $this->db->get_where('rooms', array('room_number' => $room_data), 1);
if($query->num_rows()>0) {
foreach ($query->result() as $row) {
return $row->due_amount;
}
}
This is the Controller:
function search_by_number() {
$room_data = $this->input->post('room_number');
$due_amount = $this->payments_model->get_by_room_number($room_data);
$this->index();
}
This is the View: (new_payment.php)
<?php echo form_open('payments/search_by_number'); ?>
<?php $data = array(
'name' => 'total_amount',
'id' => 'appendedPrependedInput',
'class' => 'span2',
'value' => $due_amount
); // Line Number 148
echo form_input($data);
?>
<?php echo form_close(); ?>
Try like
$data['due_amount'] = $this->payments_model->get_by_room_number($room_data);
and try to sent it to view like
$this->load->view('view_file',$data);
and at your view file echo it like
echo $due_amount;
assuming that $data is the array that you are passing to your view from your controller function.You cont pass a variable from controller to view.You need to pass it through an array data and then you can get the variable with that variable name
You should assign due_amount to $data variable and pass it to view. Like this:
$data['room_data'] = $this->input->post('room_number');
$data['due_amount'] = $this->payments_model->get_by_room_number($data['room_data']);
$this->load->view('my_view', $data);
Then in view you could do:
print_r($room_data);
print_r($due_amount);
CodeIgniter User Guide might help you understand it better.

Categories