retrieving values from a result set ruby sqllite - sql

I ran a query as follows:
rs = conn.execute("SELECT * FROM fruits WHERE name = 'apple' AND type = 'sweet'" )
puts "Results = #{rs.inspect}"
this gives me something like
Results = [{"fruitId"=> 123, "name"=>"apple", "type"=>"sweet" }]
How do I get the fruitId out from this?
I tried this:
puts "Retrieved fruitId = #{rs['fruitId'] }"
But that results in an error:
[] no implicit conversion of string to integer
How can I get the fruitId out?
Thanks

You're getting back an array, but you want a hash to be able to use rs['fruitId']. That's what its complaining about.
Try doing this:
db = SQLite3::Database.open "test.db"
db.results_as_hash = true
Source:
http://zetcode.com/db/sqliteruby/queries/
http://www.ruby-doc.org/core-2.0/Hash.html

Its an Array of Hashes. You can access fruitId of the first item in the Array like this
Results[0]["fruitId"]
#=> 123

Related

Save array in DB when checked more than one checkbox

I have a problem greatest!! I guess that really want Array, look my console when I checked just one:
{"value_solve"=>["", "", "333", ""], "contract_number"=>["33"]}
-----
SQL (317.5ms) UPDATE "authorizations" SET "value_solve" = '', "situation" = 2 WHERE "authorizations"."contract_number" = ? [["contract_number", "33"]]
After, when I checked just one, the first:
{"value_solve"=>["111", "", "", ""], "contract_number"=>["11"]}
-----
SQL (317.5ms) UPDATE "authorizations" SET "value_solve" = '111 ', "situation" = 2 WHERE "authorizations"."contract_number" = ? [["contract_number", "11"]]
And, for last, when I just more then one:
{"contract_number"=>["11", "44"], "value_solve"=>["111", "", "", "444"]}
-----
SQL (297.7ms) UPDATE "authorizations" SET "value_solve" = '111', "situation" = 2 WHERE "authorizations"."contract_number" = ? [["contract_number", "11"]]
SQL (121.9ms) UPDATE "authorizations" SET "value_solve" = '', "situation" = 2 WHERE "authorizations"."contract_number" = ? [["contract_number", "44"]]
And this is my controller:
#selected_ids = params[:authorization][:contract_number]
#authorizations = Authorization.where("contract_number in (?)", #selected_ids)
auth_params = params[:authorization]
auth_params[:contract_number].zip(auth_params[:value_solve]).each do |contract_number, value_solve|
Authorization.where(contract_number: contract_number).update_all(value_solve: value_solve, situation: 2)
end
Just save the first value on DB, how I can save more then one value? Thanks!
As I understood, you want the contract_number with id 44 to be “associated” with value_solve == "444". If this is correct, you should remove blanks from your value_solve array:
auth_params[:contract_number].zip(auth_params[:value_solve].reject(&:blank?))...
Now 44 is being updated with the second element of value_solve, which is apparently an empty string.
See Array#zip for more details.

Active Record Query - Search Multiple Columns for Multiple Strings and Return Only if They Are All Included

I need help designing a query via Active Record & Postgresql.
• The query must search across all of the following columns...
The Model looks like this:
Collection
item_id1: String
item_id2: String
item_id3: String
item_id4: String
item_id5: String
item_id6: String
• The query needs to pass in an array of strings that need to be searched across all of the item_id fields.
• The query must also only return results of Records containing all of the strings within the array.
Note: I also have the Textacular Full Text Search gem installed. However, I tested a search that I believe is supposed to search and return matches only if the records include all of the passed in strings, and the search came up with nothing, despite records with those strings existing in my database. Like this: Collection.advanced_search('B0066AJ5TK&B0041KJSL2')
Just to clarify: You want records where each of the strings in the array are found somewhere within the six item_id fields?
There's probably a more elegant way to do this, but here's what I've got off the top of my head:
terms = ['foo', 'bar', 'baz']
conditions = []
values = {}
terms.each_with_index do |t,i|
arg_id = "term#{i}".to_sym
conditions << "(item_id1 = :#{arg_id} OR item_id2 = :#{arg_id} OR item_id3 = :#{arg_id} OR item_id4 = :#{arg_id} OR item_id5 = :#{arg_id} OR item_id6 = :#{arg_id})"
values[arg_id] = t
end
Collection.where(conditions.join(' AND '), values)
This should produce a query like this:
SELECT "collections".* FROM "collections" WHERE ((item_id1 = 'foo' OR item_id2 = 'foo' OR item_id3 = 'foo' OR item_id4 = 'foo' OR item_id5 = 'foo' OR item_id6 = 'foo') AND (item_id1 = 'bar' OR item_id2 = 'bar' OR item_id3 = 'bar' OR item_id4 = 'bar' OR item_id5 = 'bar' OR item_id6 = 'bar') AND (item_id1 = 'baz' OR item_id2 = 'baz' OR item_id3 = 'baz' OR item_id4 = 'baz' OR item_id5 = 'baz' OR item_id6 = 'baz'))
Which is long and ugly, but should get the results you want.
If you meant that the fields might contain the strings to be searched for, rather than be equal to them, you could instead use
item_id1 LIKE #{arg_id}
and
values[arg_id] = "%#{t}%"

How to get a single value in findbyPk() method in yii?

In my controller
$agent = University::model()->findByPK($university_id);
I hope it will return value of a row of value.
I want a single attribute(field3) value say university_name, (with out using findByPK), how to get it
SELECT field3 FROM table [WHERE Clause]
Try this
$usercriteria = new CDbCriteria();
$usercriteria->select = "university_name";
$usercriteria->condition = "university_id=$university_id";
$university = University::model()->findAll($usercriteria);
echo $university->university_name;
Or simply do like u did first
$agent = University::model()->findByPK($university_id);
echo $agent-> university_name;
$agent = University::model()->findByPK($university_id);
echo $agent->university_name;
It should be like this:
$agent = University::model()->findByPK($university_id)->university_name;
Try this:
$university_name = University::model()->findByPK($university_id, array('select'=>'univeersity_name'))->university_name;
#Query: SElECT university_name FROM table_name where id=x;
Instead of
$university_name = University::model()->findByPK($university_id)->university_name;
#Query: SElECT * FROM table_name where id=x;
Second query returns all the fields. So better to avoid those fields are not necessary.
in case if you need to view on the yii _views, i have implemented this on my project
i put this inside my '_view.php' at /protected/views/myTable/
$agent = University::model()->findByPK($data->id_university/*this is the PK field name*/);
echo $agent->university_name /*university field name*/;
sorry again for my bad english :o
It can be done like this:
$agent = University::model()->findAllByAttributes(array('field3'),"WHERE `id` = :id", array(':id' => $university_id));
First argument of findByAttributes is an array of attributes you wish it to return. If left empty it returns all (*).

Get data from another column where first column id is equals other and other column equals X

My problem is:
I would like to get all advertistments where id of Description column is equals with Advertistment's column.
Let's say that Advertistment column is connected with Description column.
I would like to gain all description's id where one of its column called type_of_house is equals m.
Then show all advertistment where advertistment's id is equals with description's id.
In short way: advertistment shows info about houses, descriptions store houses type D and M and I want show all advertistments with houses type of M.
This is correct sql:
SELECT * FROM advertistment, description WHERE advertistment.id_advertistment = description.id_description AND description.type_of_house = "m"
I have no idea how write it into zend. I tried something like that. This function I wrote in model folder.
public function takeAll() {
$select = $this->_db->select();
$select->from(array('a' => 'advertistment', 'd' => 'description'));
$select->where('a.id_advertistment = d.id_description AND d.type_of_house = m');
return $select->query()->fetchAll();
}
You're actually quite close. This should work:
public function takeAll() {
$select = $this->_db->select();
$select->from(array('a' => 'advertistment'));
$select->join(array('d' => 'description'), 'a.id_advertistment = d.id_description');
$select->where('d.type_of_house = ?', 'm');
return $this->_db->fetchAll($select);
}

how to get last inserted id - zend

I'm trying to get latest inserted id from a table using this code:
$id = $tbl->fetchAll (array('public=1'), 'id desc');
but it's always returning "1"
any ideas?
update: I've just discovered toArray();, which retrieves all the data from fetchAll. The problem is, I only need the ID. My current code looks like this:
$rowsetArray = $id->toArray();
$rowCount = 1;
foreach ($rowsetArray as $rowArray) {
foreach ($rowArray as $column => $value) {
if ($column="id") {$myid[$brr] = $value;}
//echo"\n$myid[$brr]";
}
++$rowCount;
++$brr;
}
Obviously, I've got the if ($column="id") {$myid[$brr] = $value;} thing wrong.
Can anyone point me in the right direction?
An aternative would be to filter ID's from fetchAll. Is that possible?
Think you can use:
$id = $tbl->lastInsertId();
Aren't you trying to get last INSERT id from SELECT query?
Use lastInsertId() or the value returned by insert: $id = $db->insert();
Why are you using fetchAll() to retrieve the last inserted ID? fetchAll() will return a rowset of results (multiple records) as an object (not an array, but can be converted into an array using the toArray() method). However, if you are trying to reuse a rowset you already have, and you know the last record is the first record in the rowset, you can do this:
$select = $table->select()
->where('public = 1')
->order('id DESC');
$rows = $table->fetchAll($select);
$firstRow = $rows->current();
$lastId = $firstRow->id;
If you were to use fetchRow(), it would return a single row, so you wouldn't have to call current() on the result:
$select = $table->select()
->where('public = 1')
->order('id DESC');
$row = $table->fetchRow($select);
$lastId = $row->id;
It sounds like it's returning true rather than the actual value. Check the return value for the function fetchAll