CodeIgniter SQLite where field IN array condition - database

I'm having some trouble trying to set a 'WHERE field IN ...' clause in CodeIgniter using SQLite. I got an array of all where clause conditions called $conditions, and added the WHERE IN clause in this way:
$this->browse_model->conditions['username IN'] = "(SELECT like_to FROM likes WHERE like_from = '".$this->user->username."')";
and inside of my browse_model I use the following code to run the query:
$get = $this->db->get_where('users', $this->conditions, 6, $_SESSION['browse_page']*6);
but somehow when I use the condition I wrote above it is giving me the following error:
Fatal error: Call to a member function execute() on a non-object in
../www/system/database/drivers/pdo/pdo_driver.php on line 193
As far as I'm concerned the 'field IN array' statement is allowed in SQLite too, so I really don't know why this isn't working. Does anyone know how to make this work?
Thanks in advance!
Greets,
Skyfe.
EDIT: Tried setting the condition in the following way and didn't get an error but neither any results:
$this->browse_model->conditions['username'] = "IN (SELECT like_to FROM likes WHERE like_from = '".$this->user->username."')";
So I guess that's still not the correct way to do it..
EDIT2: 'Fixed' it, somehow it didn't interpetate the field => value way of notating the where clause correctly for the IN statement, so defined it in a custom string:
$this->browse_model->custom_condition = username IN (SELECT like_to FROM likes WHERE like_from = '".$this->user->username."')

Their is some problem in formatting IN clause,
SELECT * FROM users WHERE gender = 'f' AND gender_preference = 'm' AND username IN (SELECT like_to FROM likes WHERE like_from = 'testtest')

Related

Apex DML won't recognise variable that SOQL does

I am new to Salesforce Development, I have tested a similar query to this in a sandbox Org which worked, however when trying to update records in the live Org I am having some issues.
The issue and context is as follows:
I am trying to update the 'Record Type' field of certain Job records through Apex DML. I have opened the Developer Console and run a query:
SELECT Name, GW_Volunteers__Campaign__c, RecordtypeId FROM GW_Volunteers__Volunteer_Job__c WHERE GW_Volunteers__Campaign__c = '7010O000001P2XIQA0' and RecordTypeId = null LIMIT 5
This works fine and will show me the first 5 job records where there is no assigned record type, which is what I want to update.
The problem is when I am opening "execute anonymous" window and entering this code:
GW_Volunteers__Volunteer_Job__c [] bjobs = [
SELECT Name, GW_Volunteers__Campaign__c, RecordTypeId FROM GW_Volunteers__Volunteer_Job__c WHERE GW_Volunteers__Campaign__c = '7010O000001P2XIQA0' and RecordTypeId = null LIMIT 5];
bjobs.RecordTypeId='0120O000000LAY6QAO';
update bjobs;
I keep getting the following error:
Line: 3, Column: 11 Variable does not exist: RecordTypeId
Unless I have missed something very obvious, I cannot figure out why this is happening. Since it recognizes that variable in the query fine and a similar query (where I also updated the RecordTypeId) in the sandbox worked.
Thank you,
YH
The problem here is, you cannot assign bjobs.RecordTypeId='0120O000000LAY6QAO';. You know, bjobs is an array of GW_Volunteers__Volunteer_Job__c.
So, what you need to do is,
GW_Volunteers__Volunteer_Job__c [] bjobs = [
SELECT Name, GW_Volunteers__Campaign__c, RecordTypeId FROM GW_Volunteers__Volunteer_Job__c WHERE GW_Volunteers__Campaign__c = '7010O000001P2XIQA0' and RecordTypeId = null LIMIT 5];
for(GW_Volunteers__Volunteer_Job__c job : bjobs)
{
job.RecordTypeId='0120O000000LAY6QAO';
}
update bjobs;
Hope, this will work.

c++ builder: getting values via ADOQuery using SELECT

The question is as for delphi coders as for c++ builder coders, cuz I'm using the same components.
I'm trying to fill labels on the form by the data from database. I do a SELECT query via TADOQuery. But when I try to get a result, I always get an error like "ADOQuery1: Field 'count' not found".
'id' passed to the function is an autoincrement field value, which is EXACTLY exists in database (it was got via DBLookupComboBox). Also, executing the query manually to show result in DBGrid is successfull.
Querying without parameters and writing 'id' value to query string fails too.
What's the problem? Here's the code.
void TSellForm::LoadData(int id) {
TADOQuery* q = DataModule1->ADOQuery1;
q->Active = false;
try
{
q->SQL->Text = "select * from drugs where(id=:id)";
q->Parameters->ParamByName("id")->Value = IntToStr(id);
q->ExecSQL();
this->LabelAvail->Caption = q->FieldByName("count")->Value;
}
catch (Exception* e) {
MessageBox(NULL, PChar(WideString(e->Message)),
L"Exception", MB_OK|MB_ICONWARNING);
}
q->SQL->Clear();
}
ExecSQL is only used for SQL statements that don't return a recordset, and to determine the results you use RowsAffected.
For SELECT statements (which return a recordset), you use Open or set Active to true.
Also, count is a reserved word in most SQL dialects (as in SELECT Count(*) FROM ..., so if you have a column with that name you're going to need to escape it, typically by using either [] or double-quotes around it or by aliasing it in the SELECT itself.
ADOQuery1->Close();
ADOQuery1->SQL->Text= "SELECT * FROM reportTble WHERE (firstName =:firstName) " ;
ADOQuery1->Parameters->ParamByName("firstName")->Value = textBox->Text ;
ADOQuery1->Open();
This is how you can use ADOQuery

How to pass a string literal parameter to a peewee fn call

I've got a issue passing a string literal parameter to a SQL function using peewee's fn construct. I've got an object defined as:
class User(BaseModel):
computingID = CharField()
firstName = CharField()
lastName = CharField()
role = ForeignKeyField(Role)
lastLogin = DateTimeField()
class Meta:
database = database
I'm attempting to use the mySQL timestampdiff function in a select to get the number of days since the last login. The query should look something like this:
SELECT t1.`id`, t1.`computingID`, t1.`firstName`, t1.`lastName`, t1.`role_id`, t1.`lastLogin`, timestampdiff(day, t1.`lastLogin`, now()) AS daysSinceLastLogin FROM `user` AS t1
Here's the python peewee code I'm trying to use:
bob = User.select(User, fn.timestampdiff('day', User.lastLogin, fn.now()).alias('daysSinceLastLogin'))
result = bob[0].daysSinceLastLogin
But when I execute this code, I get an error:
ProgrammingError: (1064, u"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 ''day', t1.lastLogin, now()) AS
daysSinceLastLogin FROM user AS t1' at line 1")
Judging from this message, it looks like the quote marks around the 'day' parameter are being retained in the SQL that peewee is generating. And mySQL doesn't like quotes around the parameter. I obviously can't leave off the quotes in the python code, so can someone tell me what I'm doing wrong please?
Update: I have my query working as intended by using the SQL() peewee command to add the DAY parameter, sans quote marks:
User.select(User, fn.timestampdiff(SQL('day'), User.lastLogin, fn.now()).alias('daysSinceLastLogin'))
But I'm not sure why I had to use SQL() in this situation. Am I missing anything, or is this the right answer?
Is there a reason you need to use an SQL function to do this?
In part because I'm not very comfortable with SQL functions, I would probably do something like this:
import datetime as dt
bob = user.get(User = "Bob") #or however you want to get the User instance
daysSinceLastLogin = (dt.datetime.now() - bob.lastLogin).days

Database character limit codeigniter

I can limit the size of characters of table field in mysql as simple
SELECT NID,LEFT(BODY, 10) AS text FROM tablename
but how can i get the same result in codeigniter Active Record
I tried this code
$this->db->select('NID, LEFT(BODY,10)');
$query = $this->db->get_where('tablename');
but not working
is it possible to make that in codeigniter Active Record ??
I've been able make it work in Codeigniter using a syntax like this:
$this->db->select('NID, LEFT(BODY,10) BODY', false);
$query = $this->db->get_where('tablename');
as stated in: http://ellislab.com/forums/viewthread/201014/#940615
adding 'false' to select, avoids the automatic backtics
also, after left(BODY, 10), you must add the name the new chopped field will use:
select('NID, LEFT(BODY,10) BODY'
otherwise, Codeigniter will output an Undefined property error.
I hope it works!

CAST error in a Where Clause

On the query below I keep getting this error:
Cannot read the next data row for the dataset DataSetProject. (rsErrorReadingNextDataRow)
It appears to be the where clause, if I take it out it seems to work. So I added a cast to the where clause with no luck. Is there something special I need to do in the where clause to get this to work? Just an FYI this is in a report that is pulling an id from the url.
SELECT new_projects.new_projectsId AS ProjectId
, new_projects.new_name AS ProjectName
, new_projects.new_Description AS ProjectDescription
FROM
new_projects
LEFT OUTER JOIN new_projectsteps
ON new_projects.new_projectsId = new_projectsteps.new_ProjectSteps2Id
LEFT OUTER JOIN Task
ON new_projectsteps.new_projectstepsId = Task.RegardingObjectId
WHERE
(new_projects.new_projectsId = cast(#id AS UNIQUEIDENTIFIER))
Thanks!
EDIT:
The id in SQL is a Unique Identifier, the value of #id is being pulled from the querystring(url). So it would look like: &id='BC02ABC0-A6A9-E111-BCAD-32B731EEDD84'
Sorry for the missing info.
I suspect the single quotes are coming through. So either don't have them there by stripping them out before being passed to your parameter or use:
WHERE new_projects.new_projectsId = CONVERT(UNIQUEIDENTIFIER, REPLACE(#id, '''', ''));
If you try a direct comparison when the GUID contains other characters, you should get:
Msg 8169, Level 16, State 2, Line 1 Conversion failed when
converting from a character string to uniqueidentifier.
If this is not what's happening, then don't say "the id in SQL is a Unique Identifier" - show ALL of the code so we can try to reproduce the problem.

Resources