Nested query in codeigniter - php

there are somethings wrong at
$this->db->where("Mark_ID,(SELECT Mark_ID FROM mark WHERE Course_ID=$Course_ID && Matric_No=$Matric_No)");
in my model?any suggestion idea?thank you.
function update_record($Course_ID,$Matric_No)
{
if($Course_ID && $Matric_No != NULL)
{
$data = array(
//'Course_ID' => $this->input->post('Course_ID'),
'Matric_No' => $this->input->post('Matric_No'),
'Student_Name' => $this->input->post('Student_Name'),
'Result_Mark_1' => $this->input->post('Result_Mark_1'),
'Result_Mark_2' => $this->input->post('Result_Mark_2'),
'Result_Mark_3' => $this->input->post('Result_Mark_3'),
'Result_Mark_4' => $this->input->post('Result_Mark_4'),
'Result_Mark_5' => $this->input->post('Result_Mark_5')
);
$this->db->where("Mark_ID,(SELECT Mark_ID FROM mark WHERE Course_ID=$Course_ID && Matric_No=$Matric_No)");
$this->db->update('mark', $data);
}
}

You need to use IN() clause
$subquery="SELECT Mark_ID FROM mark WHERE Course_ID=$Course_ID && Matric_No=$Matric_No";
$this->db->where("Mark_ID IN($subquery)",null,FALSE);
But you are using subquery from same table to update you will face the error of
you can't specify target table in update query
For this you need to give new alias to your subquery like
$subquery="SELECT t.Mark_ID FROM(
SELECT Mark_ID
FROM mark
WHERE Course_ID=$Course_ID && Matric_No=$Matric_No
) t ";
$this->db->where("Mark_ID IN($subquery)",null,FALSE);

I think you can use below code for get your result.
$this->db->select("Mark_id");
$this->db->where("Course_ID",$Course_ID);
$get_id = $this->db->get($this->tbl_user)->row();
after getting mark id simply pass it to below query.
$this->db->where('Mark_id', $get_id->Mark_id);
$this->db->update($this->tbl_user,$data);

I suggest you to make your life easier by forgetting about nested queries. If you still want to use nested query, answer posted above is correct. You need to use IN
function update_record($Course_ID,$Matric_No)
{
if($Course_ID && $Matric_No != NULL)
{
$data = array(
//'Course_ID' => $this->input->post('Course_ID'),
'Matric_No' => $this->input->post('Matric_No'),
'Student_Name' => $this->input->post('Student_Name'),
'Result_Mark_1' => $this->input->post('Result_Mark_1'),
'Result_Mark_2' => $this->input->post('Result_Mark_2'),
'Result_Mark_3' => $this->input->post('Result_Mark_3'),
'Result_Mark_4' => $this->input->post('Result_Mark_4'),
'Result_Mark_5' => $this->input->post('Result_Mark_5')
);
// pre update query
$this->db->select('Mark_id');
$this->db->where('Course_ID', $Course_ID);
$this->db->where('Matric_No', $Matric_No);
$tmp_result = $this->db->get();
$result = $tmp_result->row();
$mark_id = $result->Mark_id;
//updation
$this->db->where("Mark_ID",$mark_id);
$this->db->update('mark', $data);
}
}

Related

Codeigniter Select and (conditional) Update Query

I am using Codeigniter 3, PHP and MySQL.
I'm trying to select a record from a MySQL database, and depending on the result run an update query.
If result = 0, update.
If result = 1, do nothing.
My code so far is;
public function addData($itemId) {
$gDescription = 'test';
$gPreviewLink = 'test';
$gThumbnail = 'test';
$gPageCount = 'test';
$this->db->select('g_data');
$this->db->from('item');
$this->db->where('item_id', $itemId);
$query = $this->db->get();
$result = $query->result();
// var_dump($result) returns array(1) { [0]=> object(stdClass)#22 (1) { ["g_data"]=> string(1) "0" } }
$data = array(
'item_description' => $gDescription,
'item_preview_link' => $gPreviewLink,
'item_thumbnail' => $gThumbnail,
'item_pageCount' => $gPageCount,
'g_data' => '1',
'g_data_timestamp' => 'NOW()'
);
// if result = 0 update
if($result == '0') {
$this->db->where('item_id',$itemId);
$this->db->update('item', $data);
}
}
Is there any reason the data won't update in my database? I'm not receiving any error messages.
Any help would be appreciated.
$query->result() returns an array of objects where each object is a row from the table. (As you can see in the var_dump in your comments)
Without other changes your conditional should be
if($result->g_data == '0') { ...
That said, you should have checked earlier in the method that the database atually returned results. Also, you don't need more than one row so don't use result() use 'row()' instead
...
$query = $this->db->get();
// The following will set $result to the value of "g_data" if there
// are rows and to "0" if there are none.
$result = $query->num_rows() > 0 ? $query->row()->g_data: '0';
...
If you do the above then the conditional can remain as you have it coded
if($result == '0') {...
Executing the SELECT query means making an unnecessary extra trip to the database. Just build your 0 criteria into your UPDATE query -- if it is not satisfied, then no rows will be affected.
Code:
$data = [
'item_description' => $gDescription,
'item_preview_link' => $gPreviewLink,
'item_thumbnail' => $gThumbnail,
'item_pageCount' => $gPageCount,
'g_data' => '1'
];
$this->db->where([
'item_id' => $itemId,
'g_data' => 0
]);
$this->db->set('g_data_timestamp', 'NOW()', false);
$this->db->update('item', $data);
// return (bool)$this->db->affected_rows();
All done in a single query execution. I also took the liberty of demonstrating how to pass a MySQL function as a value using set()'s third parameter.

How to write sql to select with IF else to Zend Framework?

How can I write a query to fetch a field using if else condition. Here is the query I have tried.
$sql = $this->db->select()
->from(array('GE' => 'global_edits'), array('member_id'))
->joinLeft(array('A' => 'advertiser_revision'), 'GE.member_id=A.member_id', array())
->joinLeft(array('MC' => 'member'), 'MC.id=GE.created_by', array())
->joinLeft(array('M' => 'member'), 'M.id=GE.member_id', array('email_member' => 'email'));
$sql->where('GE.status=?', $status);
$sql->group('GE.id');
$sql->columns(array('A.member_id', 'GE.created', 'GE.rev_id', 'GE.created_by', 'GE.status', 'email_created' => 'MC.email'));
return $sql;
The field GE.created _by may be 0 in some cases. In that case I have to use the field email_member
if(GE.created _by == 0) email_member else GE.created _by
How can I implement this using zend ?

cake php insert query in loop

Hello Every one i have a function in controller which is checkout where i am submitting a form.
But i want to run insert query in a loop on bellow $this->Session->read('Cart') value is 3 but my code insert one record in table if i alert something inside loop it alerts 3 time how can i run insert query 3 time please any one help me.
Thanks in advance.
public function checkout() {
$this->loadModel("Checkout");
Configure::read();
$aorderno = $this->Checkout->find('all', array('order' => array('Checkout.id' => 'DESC'),'limit' => 1));
$this->set('aorderno',$aorderno);
foreach($aorderno as $order)
{
$myorderno=$order['Checkout']['orderno']+1;
}
$firstname = $this->request->data['checkout']['firstname'];
$this->set('firstname',$firstname);
$lastname = $this->request->data['checkout']['lastname'];
$this->set('lastname',$lastname);
if(count($this->Session->read('Cart'))>0)
{
foreach($this->Session->read('Cart') as $value)
{
$sku=$value['Product']['sku'];
$this->Checkout->save(array('orderno' => $myorderno,'firstname' => $firstname,'lastname' => $lastname'sku' => $sku));
}
}
}
I supposed in your $this->Checkout->saveQuery function.
You are using something like $this->save();
Before $this->save(), call $this->create();
Hope it helps.
You can use saveMany
foreach(.......){
$arr[]= array('orderno' => $myorderno,'firstname' => $firstname,'lastname' => $lastname'sku' => $sku);
}
$this->Checkout->saveMany($arr, array('deep' => true));

how to get records from one column that is not in another column codeigniter

hi i am using codeigniter , and i have a table like this
i want to get all records where PreferenceID value is not in PreferenceParentID column
in this case i am fitering table also with the EntityID . and PreferenceParentID shoul be != 0
suppose i filter by entityID 53
my results shoul be
Couture , Denims
because PreferenceID is not in PreferenceParentID in both cases . i tried with where_not_in() but could not do . please help
this is my query
$table = $this->mastables['shop_profile_preferences'];
$this->db->select('a.ProfilePreferenceID');
$this->db->from($table." as a");
$where2 = "(SELECT a.PreferenceParentID FROM ".$table.")";
$this->db->where_not_in('a.PreferenceID', $where2);
$this->db->where("a.EntityID",$shop_id);
$this->db->where('a.PreferenceParentID !=',0);
$query=$this->db->get();
if($query->num_rows()>0)
{
return $query->result_array();
}
else
{
return FALSE;
}
the result of my query is
Array
(
[0] => Array
(
[ProfilePreferenceID] => 274
)
[1] => Array
(
[ProfilePreferenceID] => 275
)
[2] => Array
(
[ProfilePreferenceID] => 276
)
)
how to use where_not_in() properly . or ids there any other methods . please help .....
thanks in advance .
UPDATE
$table = $this->mastables['shop_profile_preferences'];
$this->db->select('a.ProfilePreferenceID,a.ProfilePreferenceValue');
$this->db->from($table." as a");
$this->db->where('a.PreferenceParentID !=',0);
$this->db->where('a.PreferenceID NOT IN (SELECT a.PreferenceParentID FROM '.$table.')', NULL, FALSE);
$this->db->where("a.EntityID",$shop_id);
$query=$this->db->get();
if($query->num_rows()>0)
{
return $query->result_array();
}
else
{
return FALSE;
}
You can't do that with CodeIgniter's where_not_in(). Because the second argument is supposed to be an array and not a string like that.
What you can do is instead use the usual where() method.
$this->db->where('a.PreferenceID NOT IN (SELECT a.PreferenceParentID FROM `table_name`)', NULL, FALSE);
In case you're wondering, the third argument in the code above is to prevent CodeIgniter from trying to protect the field and table name with backticks.

$this->db->insert_id() seems to be wiping away my previous insert_id variables value

Here is the code:
$the_question = $_POST['question'];
$the_answer = $_POST['answer'];
$dummy_num[] = $_POST['dummy_answer_1'];
$dummy_num[] = $_POST['dummy_answer_2'];
$dummy_num[] = $_POST['dummy_answer_3'];
//Get Hidden Test ID and Q_order
$test_id = $_POST['test_id'];
$q_order = $_POST['q_order'];
//Submit Question
$data_submit_q = array (
'type' => 1,
'question' => $the_question,
'done' => 1
);
$this->db->where('test_id', $test_id);
$this->db->where('q_order', $q_order);
$this->db->update('questions', $data_submit_q);
$question_id = $this->db->insert_id();
$time_created = date('Y-m-d H:i:s');
//Submit Answer
$data_submit_a = array (
'test_id' => $test_id,
'question_id' => $question_id,
'option' => $the_answer,
'company_id' => $data['company']->id,
'job_id' => $data['session_job_id'],
'time_created' => $time_created
);
$this->db->insert('options', $data_submit_a);
$answer_id = $this->db->insert_id();
//Let question know that answer is right.
$data_submit_qr = array (
'answer_id' => $answer_id
);
$this->db->where('id', $question_id);
$this->db->where('test_id', $test_id);
$this->db->update('questions', $data_submit_qr);
Setting the answer id removes the value of the question id, then on updating the database the answer id has no value also. Even though it does right before.
The method $this->db->insert_id() retrieves the ID when performing database inserts (as the name hints).
You're using it after an update, that's why your $question_id gives problems (I think it would be set to FALSE, but I don't know for sure what does that method return when called on the wrong context). WHen you do your last update you use this as a WHERE condition, and if it is not set...
It's not that your second call to insert_id() wipes out the first, I suspect is more like the first one is already NOT SET (or FALSE)
It seems that there is a bug with insert_id, you can try using:
$query = $this->db->query('SELECT LAST_INSERT_ID()');
$row = $query->row_array();
$lastInsertId = $row['LAST_INSERT_ID()'];
Hope it helps

Categories