Laravel retrieving column value from query gives error - mysql

I am currently working on a school project and am trying to retrieve values from a successfully ran query. The query is as so:
$airportQuery = Airport::where('id', '=', $airport)->get(); //Returns all columns of users selected airportId
I am trying to retrieve a column "extendedcenterlineLong" and "extendedcenterlineLat". I am doing this by running
array[] = $airportQuery->extendedcenterLong;
array[] = $airportQuery->extendedcenterLat;
(The array isn't named array[] either) When I try to run myQuery I get this error
I have not been able to fix this issue, what am I doing wrong?
Many Thanks!
EDIT: I also have these queries to get the previous row or next row from waht the user selects
$previous = Airport::where('id', '<', $airport)->max('id'); //Returns the previous rows values from users current selected airportId
$next = Airport::where('id', '>', $airport)->min('id'); //Returns the next rows values from users current selected airportId
EDIT: I solved the problem by doing $airportQuery->first()->column_name. For some reason when I printed out $airportQuery there were two items that were arrays of the column info that were identical to each other, a copy basically.

You can just do a
$airportQuery = Airport::where('id', '=', $airport)->first();
i guess above should work.

Related

mysql queries whose results are not quite right

I have a database :
I want to retrieve data with conditions where the card number is 7689, with product ID 73 or 71.
$this->cekModel->where('card_number', 7689)->where('id_product ', '73')orWhere('id_product', '71')->FindAll();
The result must display 2 data, i.e. which has id = 1 and id = 4 but I only get one data using the query above
Doesn't whereIn() do what you want?
$this->cekModel
->where('card_number', 7689)
->whereIn('id_product', array(71, 73))
->FindAll();
$this->cekModel
->where('card_number', 7689)
->whereIn('id_product', array(71, 73))
->FindAll();
The code above does not work correctly on my console (returns wrong results).
I tried modification and it worked.
$data=['71','73'];
$this->cekModel
->where('card_number', 7689)
->whereIn('id_product', $data)
->FindAll();
Thank you..

Searching MySQL for part of an array

Im trying to take an array of titles from the column 'list' and then get details for every title on said list.
//Get list
$r=$link->prepare('SELECT list FROM lists WHERE user=? LIMIT 1');
$r->bindValue(1,$user,PDO::PARAM_STR);
$r->execute();
$list=$r->fetchAll(PDO::FETCH_ASSOC);
//See how many titles the list has
$list_length=count($list);
//Get details for every title
for($i=0;$i<$list_length;$i++)
{
$r2=$link->prepare('SELECT * FROM details WHERE title=?');
$r2->bindValue(1,$list[$i],PDO::PARAM_STR);
$r2->execute();
$details=$r2->fetchAll(PDO::FETCH_ASSOC);
}
return json_encode($details);
As it is I get echoed just [].
I also get Notice: Array to string conversion in $r2->bindValue(1,$list[$i],PDO::PARAM_STR);
You have to learn to read your code, instead of asking others to do it for you.
SELECT list FROM lists WHERE user=? LIMIT 1
Look at this query. Does it looks like one that can return an array of rows?
Learn SQL. And JOINS particularly
And here goes the code
$sql = 'SELECT details.* FROM lists JOIN details on title=list WHERE user=?';
$stm = $link->prepare($sql);
$stm->execute([$user]);
json_encode($stm->fetchAll(PDO::FETCH_ASSOC));
Just FOUR lines

Simple perl mysql query not working

I've been out of the mysql and perl game for quite a few years and can't seem to get this right. I have a table with just 3 columns. 'cnt' is one of them. All I want to do is query the table on 'name' and see if name exists. If it does, I want to capture the value of 'cnt'. The table has a record of testName with a value of 2 I added manually. When this script is run it returns empty.
my $count;
my $pop = qq(SELECT cnt FROM popular WHERE name="testName");
my $sth = $dbh->prepare($pop);
$sth->execute() or die $dbh->errstr;
my #return;
while (#return = $sth->fetchrow_array()) {
$count = $return[1];
}
print "our return count is $count";
Is it obvious to anyone what I did wrong?
You probably mean
$count = $return[0];
According to perl doc on mysql
An alternative to fetchrow_arrayref. Fetches the next row of data and returns it as a list containing the field values.
Since you select cnt as the return value ,so , the size of #return is 1,but you misunderstand it as the number of results which meets your query condition.No, it is not so!Please have a more careful reading of perl doc.

Loop through query results without loading them all in array in Codeigniter [duplicate]

The normal result() method described in the documentation appears to load all records immediately. My application needs to load about 30,000 rows, and one at a time, submit them to a third-party search index API. Obviously loading everything into memory at once doesn't work well (errors out because of too much memory).
So my question is, how can I achieve the effect of the conventional MySQLi API method, in which you load one row at a time in a loop?
Here is something you can do.
while ($row = $result->_fetch_object()) {
$data = array(
'id' => $row->id
'some_value' => $row->some_field_name
);
// send row data to whatever api
$this->send_data_to_api($data);
}
This will get one row at the time. Check the CodeIgniter source code, and you will see that they will do this when you execute the result() method.
For those who want to save memory on large result-set:
Since CodeIgniter 3.0.0,
There is a unbuffered_row function,
All the methods above will load the whole result into memory (prefetching). Use unbuffered_row() for processing large result sets.
This method returns a single result row without prefetching the whole result in memory as row() does. If your query has more than one row, it returns the current row and moves the internal data pointer ahead.
$query = $this->db->query("YOUR QUERY");
while ($row = $query->unbuffered_row())
{
echo $row->title;
echo $row->name;
echo $row->body;
}
You can optionally pass ‘object’ (default) or ‘array’ in order to specify the returned value’s type:
$query->unbuffered_row(); // object
$query->unbuffered_row('object'); // object
$query->unbuffered_row('array'); // associative array
Official Document: https://www.codeigniter.com/userguide3/database/results.html#id2
Well, the thing is that result() gives away the entire reply of the query. row() simply fetches the first case and dumps the rest. However the query can still fetched 30 000 rows regardles of which function you use.
One design that would fit your cause would be:
$offset = (int)#$_GET['offset'];
$query = $this-db->query("SELECT * FROM table LIMIT ?, 1", array($offset));
$row = $query->row();
if ($row) {
/* Run api with values */
redirect(current_url().'?offset'.($offset + 1));
}
This would take one row, send it to api, update the page and use the next row. It will alos prevent the page from having a timeout. However it would most likely take a while with 30 000 records and refreshes, so you may wanna adjust your LIMIT ?, 1 to a higher number than 1 and go result() and foreach() multiple apis per pageload.
Well, there'se the row() method, which returns just one row as an object, or the row_array() method, which does the same but returns an array (of course).
So you could do something like
$sql = "SELECT * FROM yourtable";
$resultSet = $this->db->query($sql);
$total = $resultSet->num_rows();
for($i=0;$i<$total;$i++) {
$row = $resultSet->row_array($i);
}
This fetches in a loop each row from the whole result set.
Which is about the same as fetching everyting and looping over the $this->db->query($sql)->result() method calls I believe.
If you want a row at a time either you make 30.000 calls, or you select all the results and fetch them one at a time or you fetch all and walk over the array. I can't see any way out now.

How to get Ruby MySQL returning PHP like DB SELECT result

So I use the PDO for a DB connection like this:
$this->dsn[$key] = array('mysql:host=' . $creds['SRVR'] . ';dbname=' . $db, $creds['USER'], $creds['PWD']);
$this->db[$key] = new PDO($this->dsn[$key]);
Using PDO I can then execute a MySQL SELECT using something like this:
$sql = "SELECT * FROM table WHERE id = ?";
$st = $db->prepare($sql);
$st->execute($id);
$result = $st->fetchAll();
The $result variable will then return an array of arrays where each row is given a incremental key - the first row having the array key 0. And then that data will have an array the DB data like this:
$result (array(2)
[0]=>[0=>1, "id"=>1, 1=>"stuff", "field1"=>"stuff", 2=>"more stuff", "field2"=>"more stuff" ...],
[1]=>[0=>2, "id"=>2, 1=>"yet more stuff", "field1"=>"yet more stuff", 2=>"even more stuff", "field2"=>"even more stuff"]);
In this example the DB table's field names would be id, field1 and field2. And the result allows you to spin through the array of data rows and then access the data using either a index (0, 1, 2) or the field name ("id", "field1", "field2"). Most of the time I prefer to access the data via the field names but access via both means is useful.
So I'm learning the ruby-mysql gem right now and I can retrieve the data from the DB. However, I cannot get the field names. I could probably extract it from the SQL statement given but that requires a fair bit of coding for error trapping and only works so long as I'm not using SELECT * FROM ... as my SELECT statement.
So I'm using a table full of State names and their abbreviations for my testing. When I use "SELECT State, Abbr FROM states" with the following code
st = #db.prepare(sql)
if empty(where)
st.execute()
else
st.execute(where)
end
rows = []
while row = st.fetch do
rows << row
end
st.close
return rows
I get a result like this:
[["Alabama", "AL"], ["Alaska", "AK"], ...]
And I'm wanting a result like this:
[[0=>"Alabama", "State"=>"Alabama", 1=>"AL", "Abbr"=>"AL"], ...]
I'm guessing I don't have the way inspect would display it quite right but I'm hoping you get the idea by now.
Anyway to do this? I've seen some reference to doing this type of thing but it appears to require the DBI module. I guess that isn't the end of the world but is that the only way? Or can I do it with ruby-mysql alone?
I've been digging into all the methods I can find without success. Hopefully you guys can help.
Thanks
Gabe
You can do this yourself without too much effort:
expanded_rows = rows.map do |r|
{ 0 => r[0], 'State' => r[0], 1 => r[1], 'Abbr' => r[1] }
end
Or a more general approach that you could wrap up in a method:
columns = ['State', 'Abbr']
expanded_rows = rows.map do |r|
0.upto(names.length - 1).each_with_object({}) do |i, h|
h[names[i]] = h[i] = r[i]
end
end
So you could collect up the rows as you are now and then pump that array of arrays through something like what's above and you should get the sort of data structure you're looking for out the other side.
There are other methods on the row you get from st.fetch as well:
http://rubydoc.info/gems/mysql/2.8.1/Mysql/Result
But you'll have to experiment a little to see what exactly they return as the documentation is, um, a little thin.
You should be able to get the column names out of row or st:
http://rubydoc.info/gems/mysql/2.8.1/Mysql/Stmt
but again, you'll have to experiment to figure out the API. Sorry, I don't have anything set up to play around with the MySQL API that you're using so I can't be more specific.
I realize that php programmers are all cowboys who think using a db layer is cheating, but you should really consider activerecord.