How to skip quotes from code igniter active record update in order to use if condition in update? - codeigniter

I am writing query like this :-
$data = array(
'company_billing' => "if (company_billing = $userId, (NULL), $userId)",
'company_admin' => "if (company_admin = $userId, (NULL), $userId)",
);
$this->db->where('id', $organizationId);
$this->db->update('organization', $data);
I was expecting something like :-
UPDATE `organization` SET `organization`.`company_billing` = if (company_billing = 2, (NULL), 2), `organization`.`company_admin` = if (company_admin = 2, (NULL), 2) WHERE `id` = 1
But I am getting :-
UPDATE `organization` SET `organization`.`company_billing` = 'if (company_billing = 2, (NULL), 2)', `organization`.`company_admin` = 'if (company_admin = 2, (NULL), 2)' WHERE `id` = 1
I want to skip those quotes around if condition block.
Is there any way to achieve this or I will have to write native query?
Thanks

::update and ::insert function values are escaped automatically producing safer queries.
$this->db->set('company_billing' , "if (company_billing = $userId, (NULL), $userId)", false);
$this->db->set('company_admin', "if (company_admin = $userId, (NULL), $userId)", false);
$this->db->where('id', $organizationId);
$this->db->update('organization');

Related

Doctrin's Query Builder. Query with AND in where clause

I have a query in Query Builder in Doctrine. My query is:
$result = $this->entityManager->createQueryBuilder()
->select('cc', 'cct', 'cces')->from('App\Http\Entities\Cic\CaseCategory', 'cc')
->innerJoin('cc.type', 'cct')
->leftJoin('cc.eventSubject', 'cces')
->orderBy('cc.title')
->where('cc.active = 1')
->getQuery();
How Could I get query with AND clause? I mean to replace cc.active = 1 AND system_category=1' instead cc.active = 1 in where clause.
I'm trying in that way:
$result = $this->entityManager->createQueryBuilder()
->select('cc', 'cct', 'cces')->from('App\Http\Entities\Cic\CaseCategory', 'cc')
->innerJoin('cc.type', 'cct')
->leftJoin('cc.eventSubject', 'cces')
->orderBy('cc.title')
->where('cc.active = 1 AND system_category=1')
->getQuery();
But in that way it's dosen't work. How could I do that correctly?
I would be greateful for help.
Best regards
try this:
$result = $this->entityManager->createQueryBuilder()
->select('cc', 'cct', 'cces')->from('App\Http\Entities\Cic\CaseCategory', 'cc')
->innerJoin('cc.type', 'cct')
->leftJoin('cc.eventSubject', 'cces')
->orderBy('cc.title')
->where('cc.active = 1')
->andWhere('system_category=1')
->getQuery();
I suggest to you to use parameters like this:
$result = $this->entityManager->createQueryBuilder()
->select('cc', 'cct', 'cces')->from('App\Http\Entities\Cic\CaseCategory', 'cc')
->innerJoin('cc.type', 'cct')
->leftJoin('cc.eventSubject', 'cces')
->orderBy('cc.title')
->where('cc.active = :active')
->andWhere('system_category=:system_category')
->setParameters(
[
'active' => 1,
'system_category' => 1
]
)
->getQuery();

Query Builder reading conditional like a column - Unknown column in field list

I have a MySQL expression that uses a conditional IF statement. As a MySQL expression, it returns TRUE or FALSE, but when I use it in CodeIgniter's query builder, I get an error. The error suggests that the outcome of the conditional is reading like a column, but how can I fix this? Thanks.
MySQL:
SELECT
positions.max_vol AS attendee_limit,
COUNT(users_positions.user_id) AS total_attendees,
IF(COUNT(users_positions.user_id) < positions.max_vol
OR positions.max_vol IS NULL,
TRUE,
FALSE) AS result
FROM
positions
INNER JOIN
users_positions ON positions.id = users_positions.position_id
WHERE
positions.id = 16
AND users_positions.calendar_date = '2016-09-05'
Function:
private function check_attendee_limit($pos_id = NULL, $date = NULL)
{
$this->db->select('positions.max_vol, COUNT(users_positions.user_id), IF(COUNT(users_positions.user_id) < positions.max_vol OR positions.max_vol IS NULL, TRUE, FALSE)');
$this->db->from('positions');
$this->db->join('users_positions', "positions.id = users_positions.position_id", 'inner');
$this->db->where('positions.id', $pos_id);
$this->db->where('users_positions.calendar_date', $date);
$query = $this->db->get();
return $query->result(); // return the rows selected
}
Error:
A Database Error Occurred
Error Number: 1054
Unknown column 'TRUE' in 'field list'
SELECT `positions`.`max_vol`, COUNT(users_positions.user_id), IF(COUNT(users_positions.user_id) < positions.max_vol OR positions.max_vol IS NULL, `TRUE`, FALSE)
FROM `positions`
INNER JOIN `users_positions` ON `positions`.`id` = `users_positions`.`position_id`
WHERE `positions`.`id` = '15'
AND `users_positions`.`calendar_date` = '2016-09-05'
Filename: models/projects/Calendar_model.php
Line Number: 141
CI adds backticks - which means you've to prevent CI from escaping your select
Try this instead
$this->db->select('positions.max_vol, COUNT(users_positions.user_id), IF(COUNT(users_positions.user_id) < positions.max_vol OR positions.max_vol IS NULL, TRUE, FALSE)', false);
If you are worry about security - in your case it doesn't matter because you don't use any user input in your select query.
You can find more informations about the Query Builder here

CodeIgniter ActiveRecord adding a random id field

$updatedOrder = array(
'ship_status' => 'shipped',
'shipped_carrier' => (string)$selectedShipper->shipper->name,
'base_rate' => (float)$selectedShipper->rate,
'discount_rate' => (float)$selectedShipper->rate,
'tracking_number' => '123',
);
$this->orders_m->where('id', $tmpOrder->id)
->update('orders', $updatedOrder);
This yields the following SQL query: UPDATE default_orders SET ship_status = 'shipped', shipped_carrier = 'UPS Next Day Air', base_rate = 22.85, discount_rate = 22.85, tracking_number = '123' WHERE id = '1' AND id = 'orders'
Where did that last bit come from? id='orders'?
Just make sure that $tmpOrder->id is a variable and not an array.
var_dump($tmpOrder->id);
Maybe there is an error somewhere where you are getting the $tmpOrder and it returns an array for that.

Getting Error Message For oci_execute() Error (PHP)

I would like to get the specific error message if a query fails in Oracle 10g. For MySQL, PHP has the mysql_error() function that can return details about why a query failed. I check the php.net manual for the oci_execute() function, but from what I see it only returns false on fail.
I tried using oc_error(), but I am not getting anything from it.
Here is a code sample:
$err = array();
$e = 0;
//Cycle through all files and insert new records into database
for($f=0; $f<sizeof($files); $f++)
{
$invoice_number = $files[$f]['invoice_number'];
$sold_to = $files[$f]['sold_to'];
$date = $files[$f]['date'];
$sql = "insert into invoice (dealer_id, invoice_number, invoice_date)
values ('$sold_to', '$invoice_number', '$date')";
$stid = oci_parse($conn, $sql);
$result = oci_execute($stid);
//If query fails
if(!$result)
{
$err[$e] = oci_error();
$e++;
}
}
print_r($err);
Response for print_r($err):
Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => [7] => [8] => )
Have you tried to pass $stid to oci_error?
$err[$e] = oci_error($stid);
The oci_error() function takes an argument that specifies the context of your error. Passing it no argument will only work for certain kinds of connection errors. What you want to do is pass the parsed statement resource, like so:
$err = oci_error($stid);
(Note also that the return value from oci_error is an array, so I assigned the entire output to your $err array variable)

Codeigniter - brackets with activerecord?

How to have round brackets symbol in Codeigniter's active record SQL queries?
e.g. how to accomplish
SELECT * FROM `shops` WHERE (`shopid` = '10' OR `shopid` = '11') AND `shopid` <> '18'
$where="(`shopid` = '10' OR `shopid` = '11')";
$this->db->where($where, NULL, FALSE);
and for the AND condition use
$this->db->where('shopid <>', '18')
ie
$where="(`shopid` = '10' OR `shopid` = '11')";
$this->db->where($where, NULL, FALSE);
$this->db->where('shopid <>', '18')
I think you could do something like:
$where = "(`shopid` = '10' OR `shopid` = '11')";
$this->db->where($where) // or statement here
->where('shopid <>', '18') // chaining with AND
->get('shops');
Not entirely sure about the syntax, I'm writing this off the top of my head. I'll take a look at it when I get home if this doesn't work.
You can just do something like:
$this->db->select('field')->from('shops')->where("(`shopid` = '10' OR `shopid` = '11'")->where("`shopid` <> '18'");
$query = $this->db->get();
You can write your own clauses
manually:
$where = "name='Joe' AND status='boss'
OR status='active'";
$this->db->where($where);
Source: http://www.codeignitor.com/user_guide/database/active_record.html#where
$this->db->select()
->from('shops')
->where("'(`shopid` = '10' OR `shopid` = '11')")
->where('shopid !=', 18);
$this->db->get()->result();

Resources