How to find a last inserted value from procedure in codeigniter - codeigniter

I am trying get a last inserted value but I'm getting the error:
"Incorrect number of arguments for PROCEDURE hssl.insert_brouchermaster; expected 2, got 3"
Procedure
BEGIN
INSERT INTO `brouchermaster`(`broucher_name`,`order_number`) VALUES (brouchername,orderno,NOW());
SET #inserted_instance_id = LAST_INSERT_ID();
END
Model:
$insert_result = $this->db->query("CALL insert_brouchermaster('".$broucher_name."', '".$order_number."', #inserted_instance_id)");
$last_insert_query = $this->db->query("SELECT #inserted_instance_id");

The CI function db->query('your query here') returns either true or false so it isn't going to return #inserted_instance_id for you. I think you'll need to change
$insert_result = $this->db->query("CALL insert_brouchermaster('".$broucher_name."', '".$order_number."', #inserted_instance_id)");
to this
$this->db->query("CALL insert_brouchermaster('".$broucher_name."', '".$order_number."'");
//and add this line
$new_id = $this->db->insert_id();
That said, I've not had not used stored procedures very often, and not for awhile, so my syntax may be faulty. Never the less, use insert_id() to get what your after.
Documentation on the function here
Also see this SO question

Related

removing redundant queries from laravel / eloquent

In a laravel code base I'm working with there's this line of code:
if ($limit === '-1') {
$items = $query->get();
if ($items->count() < 1) {
return Paginator::make([], 0, Config::get('api.result_limit'));
}
return $query->paginate($items->count());
}
$query is a \Illuminate\Database\Eloquent\Relations\HasManyThrough object.
Anyway, the problem is that a SELECT table_name.* is being performed twice. $query->get() does it and then $query->paginate does a SELECT COUNT(*) (which itself is redundant since we already have the count from the first query) and a SELECT table_name.*, table_name.*. ie. it's just excessively redundant and I'm trying to remove that redundancy.
Here's what I tried.
return $items right after $query->get(). Unfortunately, doing so yielded the following error:
Call to undefined method Illuminate\Database\Eloquent\Collection::getCollection()
$query->paginate() returns a \MyApp\Services\Pagination\Paginator object which itself extends (\Illuminate\Pagination\Paginator) whereas $query->get() returns a \Illuminate\Database\Eloquent\Collection object.
If I could somehow convert \Illuminate\Database\Eloquent\Collection to \Illuminate\Pagination\Paginator I think that'd do the trick but if that is possible idk how.
Doing return $query->paginate(99999999) right after the if ($limit === '-1'). That works but I'd rather not specify a hard limit. I don't specify a limit when doing a SELECT with SQL I'm writing and I don't think I should have to specify one here either. I tried return $query->paginate(-1) but that gave an error.
Any ideas?

how to reference function parameter in query?

In the declared function definition I want to use value of function parameter item_account_id in the select query's WHERE clause .
CREATE OR REPLACE
FUNCTION UPDATE_CURRENT_BALANCE( item_account_id IN item_account.item_account_id%TYPE)
RETURN boolean
AS
BEGIN
if item_data_table_id = 10 then
select current_balance_curr_id
from BANK_ACCOUNT
where item_account_id = item_account_id;
end if;
RETURN true;
END UPDATE_CURRENT_BALANCE;
You have a scoping issue because the parameter name is the same as the column. The way Oracle's name resolution works, both these item_account_id = item_account_id will identify the table column. Even it we added a table alias and used it in the one side of the equality operation Oracle will still evaluate it as 1 = 1.
The solution is simple: rename the parameter. Using a prefix is popular:
CREATE OR REPLACE FUNCTION UPDATE_CURRENT_BALANCE
( p_item_account_id IN item_account.item_account_id%TYPE)
RETURN boolean
AS
BEGIN
if item_data_table_id = 10 then -- the posted code has no source for this? perhaps it's another parameter?
select current_balance_curr_id
from BANK_ACCOUNT
where item_account_id = p_item_account_id;
end if;
RETURN true;
END UPDATE_CURRENT_BALANCE;
I presume item_data_table_id is another parameter which got lost in transcription. You should prefix that too: consistency is a good thing in naming conventions.

Weird backticks behaviour in Active Record in CodeIgniter 2.0.3

Previously my all queries were running fine in CI version 2.0 but when I upgraded to 2.0.3 some of my SELECT queries were broken.
CI is adding backticks (``) automatically, but in older version its running as it is.
CI user manual have instructed to add second parameter in
db->select
as
FALSE
but still it's not working.
Code is as following:
class Company_model extends MY_Model
{
----------------
$this->db->select(' count('.$fieldname. ') as num_stations');
$this->db->select(" CONCAT_WS(',', clb_company.address1, clb_company.address2, clb_company.city, clb_company.state, clb_company.zipcode ) as companyAddress");
$this->db->from($this->_table);
$this->db->join($this->_table_device, $fieldname1. " = ". $fieldname2, 'LEFT');
$this->db->where($blablafield , '0');
----------------
The error is as follows:
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near
'FROM (`clb_device`) JOIN `clb_company` ON `clb_company`.`id` = `clb_device`.`com' at line 2
SELECT `clb_device`.`id` as deviceId, `clb_pricing_specifications`.`name` as pricingSpecName, `clb_company`.`name` as companyName, `clb_device`.`mac_address` as deviceMacAddress,
`clb_device`.`reseller_model_number` as deviceModelNumber, `clb_pricing_spec_grouping`.`pricing_master_spec_id` as pricingSpecId, `clb_device`.`address` as deviceAddress,
`clb_device`.`is_home` as deviceIsHomeCharger, CONCAT(clb_company.portal_line1, `'/'`, `clb_device`.`name)` as deviceDisplayName FROM (`clb_device`) JOIN `clb_company`
ON `clb_company`.`id` = `clb_device`.`company_id` LEFT JOIN `clb_pricing_group_devices` ON `clb_device`.`id` = `clb_pricing_group_devices`.`device_id` and clb_pricing_group_devices.is_active = 1
LEFT JOIN `clb_pricing_spec_grouping` ON `clb_pricing_group_devices`.`pricing_spec_id` = `clb_pricing_spec_grouping`.`pricing_master_spec_id` LEFT JOIN `clb_pricing_specifications` ON
`clb_pricing_spec_grouping`.`pricing_spec_id` = `clb_pricing_specifications`.`id` WHERE clb_company.vendor_id is not null AND cast(substr(clb_devi
ce.software_version, 1, 3) as decimal(2,1)) > 2.0 AND clb_device.device_state > 0 GROUP BY `clb_device`.`id` ORDER BY CONCAT(trim(clb_company.portal_line1), `'/'`, trim(clb_device.name)) desc LIMIT 20
Have a look at CONCAT(trim(clb_company.portal_line1), `'/'`, trim(clb_device.name))
Please suggest the workaround.
Use this line before your query:
$this->db->_protect_identifiers=false;
This will stop adding backticks to the built query.
The solution is very simple:
In the database configuration file (./application/config/database.php) add a new element to array with default settings.
$db['default']['_protect_identifiers']= FALSE;
This solution is working for me and more elegant and professional.
All other answers are really old, this one works with CI 2.1.4
// set this to false so that _protect_identifiers skips escaping:
$this->db->_protect_identifiers = FALSE;
// your order_by line:
$this -> db -> order_by('FIELD ( products.country_id, 2, 0, 1 )');
// important to set this back to TRUE or ALL of your queries from now on will be non-escaped:
$this->db->_protect_identifiers = TRUE;
class Company_model extends MY_Model
{
----------------
$this->db->select(" count('$fieldname') as num_stations",false);
$this->db->select(" CONCAT_WS(',', clb_company.address1, clb_company.address2, clb_company.city, clb_company.state, clb_company.zipcode ) as companyAddress",false);
$this->db->from($this->_table);
$this->db->join($this->_table_device, $fieldname1. " = ". $fieldname2, 'LEFT');
$this->db->where($blablafield , '0');
----------------
The false you were talking about is what is needed, can you try the code above and copy and paste to us the output of
echo $this->db->last_query();
This will show us what the DB class is creating exactly and we can see whats working / what isn't. It may be something else (you haven't given the error from that is generated sometimes sql errors can be misleading.)
From the docs:
$this->db->select() accepts an optional second parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks. This is useful if you need a compound select statement.
CI will only protect your ACTIVE RECORD calls, so if you are running $this->db->query(); you will be fine, and based on the notes you should be safe with AD calls like so to disable backticks (not sure why you say they don't work, but I don't see your full code, so I can't be sure)
$this->db->select('(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4') AS amount_paid', FALSE);
$query = $this->db->get('mytable');
make sure FALSE is without single quotes (makes it a string), and it might not validate (not tested by me).
I think you should check DB_driver.php file, there is a variable named as protect_identifier, the point is when you will check with older version of CI, you will see that there is a condition which is missing in new version,escape variable which is checked for nullability, paste that condition from older version and you will be OK
CI_DB_active_record::where() has a third param for escaping, this has worked better for me than switching on and off CI_DB_driver::_protect_identifiers
public function where($key, $value = NULL, $escape = TRUE)
Not sure what CI version this was added in.
HTH someone
Here's a trick that worked for me. Replace this line
$this->db->join($this->_table_device, $fieldname1. " = ". $fieldname2, 'LEFT');
with this:
$this->db->join($this->_table_device, $fieldname1. " IN(". $fieldname2 .")", 'LEFT');
this will prevent CI from escaping your field. It's not ideal but it's better than the alternatives.
I just read a simple solution for this...
I changed the value of var $_escape_char (system/database/drivers/mysql/mysql_driver.php, line 36..
It was
var $_escape_char = '`';
Changed to
var $_escape_char = ' ';
and now it works... But i am affraid if I made any security issues..
Thanks

VB6.0 with DataControl Database Programming

Hey, can I ask you something? I'm using VB6.0 and I have some problem with the connection of my Database through DataControl. I have a table named tblEmployee and the other one is tblPosition then I passed the value of the two tables to two DataControls respectively. How can I then get the value of a certain row of Position field. With my code, my Position field returns only the first row. Here's my code
Private Sub cmdSearchEmployee_Click()
With datEmployee.Recordset
datEmployee.Recordset.Index = "idxid"
datEmployee.Recordset.Seek "=", txtIDNumber.Text
If .NoMatch = True Then
MsgBox ("No Record Found!")
Else
Me.txtLastName.Text = .Fields("lname")
Me.txtFirstName.Text = .Fields("fname")
Me.txtMiddleName.Text = .Fields("mi")
With datPosition.Recordset
Me.txtPosition.Text = .Fields("position")
End With
End If
End With
End Sub
I can't see that you have "passed the value" to your DataControl named datPosition. Could this be the problem? e.g. where you have
With datPosition.Recordset
Me.txtPosition.Text = .Fields("position")
End With
...should be more like this:
With datPosition.Recordset
.Index = "some_index??"
.Seek "=", "some_value??"
Me.txtPosition.Text = .Fields("position")
End With
Also consider using the recordsets' Filter to remove the rows that do not match your criteria then RecordCount to loop through the rows that do match your criteria.
Further consider returning a single recordset by creating a join between tblEmployee and tblPosition, either in SQL code or returning a hierarchical recordset using the MsDataShape with its SHAPE syntax.

what are the OleDbTypes associated with Oracle Number and varchar2 when calling a function

I'm trying to map OleDb parameters to an Oracle Function. I was able to do this using the System.Data.Oracle namespace but then found that this is depricated, so I thought i would re-write it as OldDb to avoid installing the Oracle Provider.
I have defined the following oracle function as an example:
create function GetImagePath (AIRSNumber in number)
return varchar2
is
begin
return '\\aiimg524\images\Ofndrtrk\2010\01\0kvrv1p000lcs74j';
end;
and I'm calling it using the following code:
using (var command = new OleDbCommand())
{
command.Connection = con;
command.CommandText = ConfigurationManager.AppSettings[OTRAK_PHOTO_FUNC];
command.CommandType = CommandType.StoredProcedure;
string parm = ConfigurationManager.AppSettings[OTRAK_PHOTO_PARM];
command.Parameters.Add(parm, OleDbType.Decimal); // maps to oracle Number
command.Parameters[parm].Direction = ParameterDirection.Input;
command.Parameters[parm].Value = airsNumber;
command.Parameters.Add(RETURN_VALUE, OleDbType.Variant); // maps to Oracle varchar2
command.Parameters[RETURN_VALUE].Direction = ParameterDirection.ReturnValue;
try
{
con.Open();
command.ExecuteNonQuery();
path = command.Parameters[RETURN_VALUE].Value.ToString();
}
I tried a bunch of different OleDB types for the parameter and the return value. the current attempt is from a mapping table i found on the web that said number = decimal and varchar2 = variant. I'm about to try every permutation of types in the enum and wanted to ask for help. the not so useful error message i get is:
[System.Data.OleDb.OleDbException] = {"ORA-06550: line 1, column 7:\nPLS-00306: wrong number or types of arguments in call to 'GETIMAGEPATH'\nORA-06550: line 1, column 7:\nPL/SQL: Statement ignored"}
This actually had nothing to do with the type of the parameters but the order. Using the OleDb provider for Oracle does not respect the names of the parameters in the parameter collection but rather the order that the parameters are added. Wwhen calling an oracle function, the return value is a free parameter that must be declared first. by adding my return value parameter and then the actual function parameter things started working.
using the command.Parameters.AddWithValue(parm, value) also simplifies things a bit.

Resources