Codeigniter: How to increase active records in the for loop? - postgresql

I'm using PostgreSQL and I have a table which includes week numbers of the year in its columns. I try to update by increasing these columns' values in nested loops.
I have the following query which attempts to increase the related field of a record.
foreach ( $updateVotes as $key => $value ) {
for ( $week = 1; $week < 53 ; $week++) {
$increaseValue = $value['week_'.$week];
$this->db->set("week_".$week , "week_".$week. " +".$increaseValue, "FALSE");
}
$this->db->where('id', $id)
->update('votes');
}
To achieve my aim, I need output like the one below:
UPDATE "votes"
SET week_1 = week_1 +20,
week_2 = week_2 +50,
...
WHERE id = 1
However, when I run the query, it produces the following SQL:
UPDATE "votes"
SET "week_1" = 'week_1 +20',
"week_2" = 'week_2 +50',
...
WHERE id = 1
As it also produces single quotes, it throws errors like this:
column 'week_1 +20' cannot found
How can I escape these single quotes and run the query successfully?

According to the official document here, you should pass FALSE (Bool) instead of "FALSE" (String) like this
$this->db->set("week_".$week , "week_".$week. " +".$increaseValue, FALSE);
Hope this helps!

Remove Double quotes from "FALSE" into FALSE

Related

getting the 1st row in a database

I want to get the 1st row of the result depends on which build the room is. For example Building 1 have 1-200 rooms and Building 2 have 201-400 rooms. The code I tried is below. I have used the MIN in the where clause but I got all the rooms instead of having one.
$query = $this->db->query("SELECT * FROM `ha_utility_reading`");
if ($query->num_rows == 0) {
echo "some data match";
$lastroom = $this->db->select("*")->from("rooms")
->where("(SELECT MIN(room_num) FROM ha_rooms) and bldg_num = '$bldg_num'")
->get()->result_array();
foreach($lastroom as $key => $test) {
$output['room_num'][] = $test['room_num'];
json_encode($output);
}
You get all the rows because you need a group by clause. Anyway, the best way to do this is just adding this to your query:
order by room_num asc limit 1;
Try this,
select * from rooms order by room_num asc limit 1;

How to do a select statement query with comma separator?

I need to do a simple query, Select Statement
I want to search in Table all record with value "ValueA, ValueB".
If I use this code, not work well:
String255 valueToFilter;
valueToFilter = 'ValueA, ValueB';
select count (RecId) from MyTable
where MyTable.Field like valueToFilter ;
But not working, I need to keep all record with value "ValueA" or "ValueB", if in the file there is value like : "ValueA, ValueC" I want to get too.
I don't know the number of values (valueToFilter).
Thanks!
From my point of view the easiest way to accomplish this is to split your filter string:
String255 valueToFilterA = 'ValueA';
String255 valueToFilterB = 'ValueB';
;
select count (RecId) from MyTable
where MyTable.Field like valueToFilterA
|| MyTable.Field like valueToFilterB;
If you don't know the number of values you should use query object to add ranges dynamically:
Query query = new Query();
QueryRun queryRun;
QueryBuildDataSource qbds;
QueryBuildRange queryRange;
container conValues;
;
qbds = query.addDataSource(tableNum(MyTable));
for (i = 1; i <= conlen(conValues); i++)
{
queryRange = qbds.addRange(fieldNum(MyTable, Field));
queryRange.value(SysQuery::valueLike(conPeek(conValues, i)));
}
queryRun = new QueryRun(query);
info(strFmt("Records count %1", SysQuery::countTotal(queryRun)));

Model returns nothing, but running Query returns records

In my controller, I have the following code:
$threads = MessageThread::whereExists(function($query) {
$messid = '`' . env('DB_PREFIX') . 'message_threads`.`id`';
$query->select(\DB::raw(1))
->from('message_thread_participants')
->where('message_thread_participants.message_thread_id', '=', $messid); // AND message_thread_participants.user_id = ' . $user_id);
})
->orderBy('message_threads.created_at', 'DESC')
->take(30)
->get();
If I print out the resulting query using DB::getQueryLog() I get the following:
[ {
"query": "select * from bd45_message_threads where exists (select 1 from bd45_message_thread_participants where
bd45_message_thread_participants.message_thread_id = ?) order by
bd45_message_threads.created_at desc limit 30",
"bindings": [
"bd45_message_threads.id"
],
"time": 1.06 } ]
And I run that query manually (substituting the binding for the ?, I get the expected 30 results..... but the code itself returns no results... I assume it's some problem between using Models and Where Exists... but it's just a guess right now.... anyone have any clue why the query would return results in Navicat or PHPMyAdmin, but the controller returns a blank array?
I'm a little late to the party, but in case someone has the same problem, it must be beacause you have to use
->whereColumn('bd45_message_thread_participants.message_thread_id', 'bd45_message_threads.id')
to compare two columns values. The ->where expects to compare a column and a value, not another column.

FQL WHERE IN with Null feedback in the array

I'm trying the command below:
SELECT * FROM mytable WHERE field IN(1,2,3, NULL, 5)
and the result is {r1,r2,r3}
I want {r1,r2,r3,NULL,r4}, how can I do that?
Thank you!
You can't. Facebook automatically filters out NULL results from the rows. There is also no guarantee that the results will be in the same order as the arguments you passed in your IN criteria.
You also can't SELECT * in FQL. You have to individually select fields to return.
You'll need to do something like this:
THINGS_TO_FIND = array (1,2,3,NULL,5)
RESULT = FQL_URL + urlencode('SELECT field1, field2 FROM table WHERE field1 IN ' + THINGS_TO_FIND')
foreach (THING in THINGS_TO_FIND) {
foreach (ITEM in RESULT) {
if THING == ITEM->field1 then OUTPUT->field1 = ITEM->field2
}
}

Having an SQL SELECT query, how do I get number of items?

I'm writing a web app in Perl using Dancer framework. The database is in sqlite and I use DBI for database interaction.
I'm fine with select statements, but I wonder is there a way to count selected rows.
E.g. I have
get '/' => sub {
my $content = database->prepare(sprintf("SELECT * FROM content LIMIT %d",
$CONTNUM));
$content->execute;
print(Dumper($content->fetchall_arrayref));
};
How do I count all items in the result without issuing another query?
What I want to achieve this way is showing 30 items per page and knowing how many pages there would be. Of course I can run SELECT COUNT (*) foo bar, but it looks wrong and redundant to me. I'm looking for a more or less general, DRY and not too heavy on database way to do so.
Any SQL or Perl hack or a hint what should I read about would be appreciated.
// I know using string concatenation for querys is bad
You have to do it the hard way: one query to get the count and another to get your desired slice of the row set:
my $count = $database->prepare('SELECT COUNT(*) FROM content');
$count->execute();
my $n = $count->fetchall_arrayref()->[0][0];
my $content = $database->prepare('SELECT * FROM content LIMIT ?');
$content->execute($CONTNUM);
#...
Not too familiar with perl, but I assume you can just store the result of $content->fetchall_arrayref and retrieve the count from that array befor you print it.
[edit]
Something like
my $ref = $content->fetchall_arrayref;
my $count = scalar(#$ref);
Don't use sqlite myself but the following might work:
select * from table join (select count(*) from table);
Whether the above works or not the first thing I'd look for is scrollable cursors if you are going to page through results - I doubt sqlite has those. However, in DBI you can use fetchall_arrayref with a max_rows to fetch a "page" at a time. Just look up the example in the DBI docs under fetchall_arrayref - it is something like this:
my $rowcache = [];
while( my $row = ( shift(#$rowcache) || shift(#{$rowcache=$sth->fetchall_arrayref(undef,100)||[]}) )
) {
# do something here
}
UPDATE: Added what you'd get with selectall_hashref assuming the table is called content with one integer column called "a":
$ perl -le 'use DBI; my $h = DBI->connect("dbi:SQLite:dbname=fred.db"); my $r = $h->selectall_hashref(q/select * from content join (select count(*) as count from content)/, "a");use Data::Dumper;print Dumper($r);'
$VAR1 = {
'1' => {
'count' => '3',
'a' => '1'
},
'3' => {
'count' => '3',
'a' => '3'
},
'2' => {
'count' => '3',
'a' => '2'
}
};
If you want to know how many results there will be, as well as getting the results themselves, all in one query, then get the count as a new value:
SELECT COUNT(*) AS num_rows, * from Table WHERE ...
Now the row count will be the first column of every row of your resultset, so simply pop that off before presenting the data.