$this->db->escape() function adding single quote in codeigniter - codeigniter

In codeigniter when i am using function $this->db->escape() while insert data, It is adding single quote in database, Can anyone please help why i am getting this issue ?
Here is my code
$data = array('company_id'=>$this->db->escape($companyID),'payor_type'=>$this->db->escape($payor_type),
'payer_type'=>$this->db->escape($payer_type),'insurance'=>$this->db->escape($insurance),
'created_date'=>date("Y-m-d H:i:s"));
$this->db->insert('tb_Payer',$data);

When you use the query builder class to construct your queries the values are escaped automatically by the system so you don't have to use the function $this->db->escape. In your case, each value was escaped by the escape function and the system did it again for each value when executing the insert function.
Now if you want to run custom queries using the function $this-db->query it is a good practice to escape the data like bellow:
$sql = "INSERT INTO table (column) VALUES(".$this->db->escape($value).")";
$this->db->query($sql);

Related

use a custom function inside a laravel select

I have a query that needs to use a custom function like is showed below.
The problem is that one of the parameters is a value of another field from the same query.
The function is "calcula_distancia" and "$ofps[0]->latitude" and "$ofps[0]->longitude" are fields from a previus query.
The function needs 4 parameters and the last two are field from $necps that is beeing selected, but I can not retrieve the value from it using just 'participantes.latitude' or even without cotes. It passes a string only, to the function.
So, how can I pass the value from this fields beeing selected to the function?
Tryed to use RAW but not work.
Sorry for the big question. thanks! :-)
use App\Classes\MinhasFuncoes;
$mf = new MinhasFuncoes();
$necps = DB::table('necessidades_part')->where('necessidades_part.id_part',"<>",$id_part)
->where(function($query) use ($searchValues){
foreach ($searchValues as $value) {
if(strlen($value)>3){
$query->orwhere('obs','like','%'.($value).'%')
->orwhere('necessidades.descricao','like','%'.($value).'%')
->orwhere('categorias.descricao','like','%'.($value).'%');
}
}
})
->join('participantes','necessidades_part.id_part','=','participantes.id')
->join('necessidades','necessidades_part.id_nec','=','necessidades.id')
->join('categorias','necessidades.id_cat','=','categorias.id')
->join('unidades','necessidades.id_unid','=','unidades.id')
->select('participantes.id as id_part','participantes.nome_part','participantes.latitude',
'participantes.longitude','participantes.nome_part','necessidades_part.id as id_nec_part',
'necessidades_part.id_nec','necessidades_part.quant','necessidades_part.data',
'necessidades_part.obs','necessidades.descricao as desc_nec',
'categorias.descricao as desc_cat','unidades.descricao as desc_unid',
$mf->calcula_distancia($ofps[0]->latitude,$ofps[0]->longitude,'participantes.latitude',
'participantes.longitude').' as distancia')
->orderBy('data','desc')
->paginate(10);
you can not execute your PHP function inside of your DB query. you should use MySQL function instead of that or you should fetch results from the database then map your result just in PHP

Laravel Query Builder: whereExists translates condition clause to question mark

If I have the following query built using the Query Builder:
$q = DB::table('Products')->whereExist(function ($q)
{
$q->select(DB::raw(1))
->from('tags_products')
->where('products.PorductId', '=', 'tags_products.ProductID');
});
The translated SQL using $q->toSql(); that is:
select * from `Products` where `exist` = (select 1 from `tags_products` where `products`.`ProductID` = ?)
Apparently, the Query Builder translates tags_products.ProductID to ?.
Why does it become "?" ?
As #Jared Eitnier very well pointed out, Laravel uses PDO to bind the parameters you pass to the Query Builder methods. However, because when you use where the third parameter represents the value, Laravel will not treat it as a column unless you explicitly tell it to, otherwise it will treat 'tags_products.ProductID' as a regular string value. So you have two options here:
1. Use DB::raw() to let the Query Builder know that the value is not a string that requires escaping:
->where('products.PorductId', '=', DB::raw('tags_products.ProductID'));
2. Use whereRaw() which will allow you to write a raw SQL statement:
->whereRaw('products.PorductId = tags_products.ProductID');
These are mysql prepared statements.
See What is the question mark's significance in MySQL at "WHERE column = ?"?
Laravel uses mysql's PDO.

codenigiter: sql injection and xss_clean

I am using active record in codenigiter to do some query and I read some docs that say using AR will escape the parameter automaticly.I want to comfirm this and I read the source code of AR class,but I am confused!
I do some test,eg,I access the url as follow is:
http://wrecruit.tudouya.com/company/editProfile/4
then I enable the profiler in CI.
when I add a single quote at the end of url as follows:
http://wrecruit.tudouya.com/company/editProfile/4'
I see the real sql statement the query execute and I got this:
SELECT *
FROM (`wy_company`)
WHERE `id` = '4%27'
the single quote is escaped to '%27',I want to know how this escape happen?maybe it's escaped by the input class?
Url adress is always encoded with urlencode function. This function replace all symbols with codes.
If you want to prevent xss you should to check you parameter. May be like this (in controller Company):
public function editProfile($id)
{
$id = (int)$id;
if($id){
// model code execute - loading DB data
}
}
And in DB query you should use Query Bindings, or use Active record. Them both are prevent injection.

Zend DbTable case insensitive

I have a login system for my webapp that works well using the Zend auth adapter but the problem is I want the email to be case insensitive when a user logs in. I am using Oracle as the back end DB and normally I would user the LOWER(EMAIL)=LOWER(:email) method. I tried to pass that Oracle function in the setIdentityColumn() but I get the error:
The supplied parameters to Zend_Auth_Adapter_DbTable failed to produce
a valid sql statement, please check table and column names for
validity.
protected function _getAuthAdapter()
{
//$dbAdapter = Zend_Db_Table::getDefaultAdapter();
$db = Zend_Registry::get('db');
$authAdapter = new Zend_Auth_Adapter_DbTable($db);
$authAdapter->setTableName('USER_TABLE')
->setIdentityColumn('LOWER(EMAIL)') //Tried to pass LOWER()
->setCredentialColumn('ENCODED_PW')
->setCredentialColumn('PASSWORD');
return $authAdapter;
}
The error is coming from the function _authenticateCreateSelect() in the Zend_Auth_Adapter_DbTable class. The problem is this part of the script:
$dbSelect->from($this->_tableName, array('*', $credentialExpression))
->where($this->_zendDb->quoteIdentifier($this->_identityColumn, true) . ' = ?', $this->_identity);
The quoteIdentifier() method is like PHP quote() and is turning a query like this:
select * from LOWER(:email)
into this:
select * from "LOWER(:email)"
Anyone see a way around this?
Kind Regards
Nathan
Try something like this:
$authAdapter->setTableName('USER_TABLE')
->setIdentityColumn(new Zend_Db_Expr('LOWER(USERID)'))
->setCredentialColumn('PASSWORD');
The problem is that if you pass 'LOWER(USERID)' as a simple string, Zend will put quotes around it, causing it to create an invalid query. Using Zend_Db_Expr will stop Zend doing this.

How to use 'IN (1,2,3)' with findAll?

I need to get a couple of Students from the database, and I have their primary keys in a comma-separated string.
Normally using SQL it would be something like:
$cleanedStudentIdStringList = "1,2,3,4";
SELECT * FROM Student WHERE id IN ($cleanedStudentIdStringList)
Yii's ActiveRecord seems to insert a single quote around bound parameters in the resulting SQL statement which cause the query to fail when using parameter binding.
This works, but doesn't use safe parameter binding.
$students = Student::model()->findAll("id IN ({$_POST['studentIds']})");
Is there a way to still use parameter binding and get only a couple of rows in a single query?
You can do it also that way:
$criteria = new CDbCriteria();
$criteria->addInCondition("id", array(1,2,3,4));
$result = Student::model()->findAll($criteria);
and use in array any values you need.
Aleksy
You can use findAllByAttributes method also:
$a=array(1,2,3,4);
$model = Student::model()->findAllByAttributes(array("id"=>$a));

Resources