Codeigniter / Active Record Class generating blank IN() - php

I have some code in Codeigniter that looks like this:
$this->db->select('email_account_id');
$this->db->where('TRIM(LOWER(email_account_incoming_username))',trim(strtolower($email_address)));
$query = $this->db->get($this->users_db.'email_account');
Throws this error:
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 ') AND TRIM(LOWER(email_account_incoming_username)) = 'email#server.co.uk'' at line 3
SELECT `email_account_incoming_username`, `email_account_id` FROM (`crmuat_users`.`email_account`) WHERE `email_account_id` IN () AND TRIM(LOWER(email_account_incoming_username)) = 'email#server.co.uk'
Now I don't for the life of me understand how the "IN()" got in there?
Anybody able to see?

You must have called the $this->db->where_in() method somewhere. It is impossible for CodeIgniter Active Record to generate the IN() clause unless you tell it to do so. Try to see if you called the method by accident before you do the select. Also note, that since the Active Record class has this characteristic of singularity in generating query, it is possible that you've called the method somewhere else withing another method that utilizes the Active Record class.
For example, the following will cause the IN() clause to be generated within the final query.
function a()
{
...
$this->db->where_in();
...
$this->b();
}
function b()
{
// Produces the same error as stated in the question because the call of
// where_in() beforehand.
$this->db->select(...)->where(...)->get(...);
}
P.S: Why are you doing trimming and converting the string into lowercase twice? It seems redundant to me.

Related

Get SQL after Zend\Db\Sql\Select

I'm on zend framework 2.
The scenario is, I want to know the actual SQL query after Zend\Db\Sql\Select. I cannot use Zend\Db\Sql\SQL here, and
$select = new Zend\Db\Sql\Select();
$select->where(array($between));
$select->prepareStatement($select)->getSQL();
is giving error like,
Call to a member function getParameterContainer() on null
What is the correct way to write it?
You need to use getSqlString() method.
More info you can find here: https://akrabat.com/displaying-the-generated-sql-from-a-zenddbsql-object/

Laravel query screws my variables

Controller:
public function getSpecificPost($id)
{
$returnArray = with(new Posts)->getSpecificPost($id);
print_r($returnArray);
}
?>
Model:
public function getSpecificPost($post_id)
{
//exit($post_id);
return DB::table('posts')->where('id', $post_id)->toSql();
}
?>
If I uncomment the exit, it gives me a 1 as return.
When I comment the exit I of course get a query, the query is as follows:
select * frompostswhereid= ?
Its Laravel Framework, help me out please!
The ? is a placeholder for your variable. It will be replaced with (in this case) 1. See the colored block on this page:
Note: The Laravel query builder uses PDO parameter binding throughout
to protect your application against SQL injection attacks. There is no
need to clean strings being passed as bindings.
You are aware of the fact that your don't actually execute the query? If you want to get the specific post with $post_id, you can change the line in your model to this one:
return DB::table('posts')->where('id', $post_id)->first();
If you want to see all executed queries (with replaced variables!) with Eloquent, you can use Laravel PHP Debugbar.

Database class object

I've seen people use this piece of code and I'm trying to understand what it does because I don't see it in any of the codeigniter documenation or in the source code for the database class.
$this->db->ar_orderby
This is an array that holds order by columns..
There should be no reason to use this property directly. Instead call $this->db->order_by('column') which appends to the array automatically.
defined in system/database/DB_active_rec.php Line 42
appended to in method CI_DB_active_record::order_by Line 856
used to generate SQL in CI_DB_active_record::_compile_select Line 1781
You mean
http://phpxref.com/xref/codeigniter/system/drivers/DB_active_record.php.source.html#l781
It allows you to specify the order by.
It still makes sense to use this in the way below -
if (!count($this->db->ar_orderby)) {
$this->db->order_by($this->order_by );
}
It basically means - If an order is not already set by db library when this method was called, use this. Prevents calling of "order by" twice.
You can replace these lines:
if (!count($this->db->ar_orderby)) {
$this->db->order_by($this->order_by );
}
with:
if(!count($this->db->order_by($this->order_by))) {
$this->db->order_by($this->order_by);
}

Yii sql query bindings, with params, do not work properly

I'm new to Yii and everything seems good, but the problem is, when I`m using the binding params, like (DAO stile):
$command = $this->conn->createCommand($sql);
$command->bindColumn("title", "test_title");
$result = $command->query();
or (Active Record):
$row = Movies::model()->find("m_id=:m_id", array(":m_id"=>27));
or
$row = Movies::model()->findByPk(24);
I've tried everything:
1) added a config param to mysql config. in main.php - 'enableParamLogging' => true
2) changed strings from ' to "
3) added another param just in case of mysql versions - 'emulatePrepare'=>true
Nothing works for me.
I thought that the problem is in params, but bindColumn method doesn't use it, so my presumption is that some module of Yii hasn't been include in config file or something like that.
My model looks like this (created in /models dir):
class Movies extends CActiveRecord {
public static function model($className = __CLASS__) {
parent::model($className);
}
}
Just for everybody to avoid unnecessary questions: the database is configured properly in main.php conf file, there is a table movies, there is a PKs 24 and 27 also.
All native SQL works fine, except using in DAO special methods to bind some params and if in AR using findByPk or find. I hope that this is clear, guys don't bother me with obvious simple technical possibilities, that I can (as U presume) did wrong.
PS Another helpful info - when calling
$command->bindColumn("title", "test_title");
FW's throwing an Exception - CDbCommand and its behaviors do not have a method or closure named "bindColumn". So, as mentioned above, I think that Yii don't see those special methods and this is certain. How can I repair it?
Ok, why this code don't work either? There is no Exceptions, just blank page.
$sql = "SELECT title, year_made FROM movies WHERE year_made=':ym'";
$command = $this->conn->createCommand($sql);
$command->bindParam(":ym", "2012", PDO::PARAM_STR);
$result = $command->query();
The DAO binding isn't working because there is no bindColumn. You only have bindParam, that binds a variable to a column, or bindValue, that binds a value.
I don't know what's wrong with the AR query though.
Edit: Your DAO code should look like this:
$sql = "SELECT * FROM sometable WHERE title = :title";
$command = $this->conn->createCommand($sql);
$command->bindParam(":title", $tile_var);
$result = $command->query();
Have you generated movie model by Gii generator or you wrote it by yourself?
Edit:
As I know you have to add tableName
public function tableName() {
return 'movies';
}
You may have two separate issues. At least your DAO code (if that is what you actually have in your code) is binding wrong.
Binding needs to occur before the query is done (and it's done on the command object), not on the result object. See more info here: http://www.yiiframework.com/doc/guide/1.1/en/database.dao#binding-parameters
As far as your AR queries go, those could also be problematic. You can use findByAttributes instead of this line (although your line should work):
$row = Movies::model()->find("m_id=:m_id", array(":m_id"=>27));
The below should work if you have a standard id key. If you don't (and are using m_id, have you set your model's primaryKey() function up?
$row = Movies::model()->findByPk(24);
Also, you'll be getting a model object back, not a row if that changes how you are handling the results ...

I am facing problem of read function in cakephp

hii..I want to edit single row.i used
$this->data = $this->BuildingProperty->read(null,$id);
but it didnt fetch the values of this id.
so what can i do. Give me any suggestion.
Why did you pass null as the first parameter? It should be a string on array of fields that you want to retrieve.
Anyway, try this instead:
$this->BuildingProperty->id = $id;
$this->data = $this->BuildingProperty->read();
The syntax which you are using is correct. First check if the $id is integer. (echo $id). Then if so, check your database if it has such record in building_properties table check if this ID exist. Finally check if the variable $this->data is populated with the proper values.
All those checks return you proper values then the problem is not in Model->read() function.
Another hint, try to clear the cache /app/tmp/cache/modules and /app/tmp/cache/persistent
Are you calling the method from a controller that knows about BuildingProperty? i.e. BuildingPropertiesController. If not, have you included a
var $uses = array('BuildingProperty');
statement in the class definition or explicitly loaded the model with, for example,
loadModel('BuildingProperty')
Your syntax is correct and the only other explanation if there is no warning or error message is that the returned array is empty, i.e. the record does not exist.
Check that you have debug turned on:
Configure::write('debug', 1); // or higher.A 2 will output SQL queries as well
then try
debug($this->BuildingProperty->read(null,$id));
You should at least get some output telling you the line of the debug call.

Categories