Hello and good morning to you all,
I am following the qickstart tutorial from Rob Allen in the manual.
I am trying to change some things. One of the things I am trying to do is to get a query like this:
"SELECT max(id) FROM Albums";
I tried things like
$this->select();
$this->columns(array('id' => 'MAX(id)'));
Apparently this is not the way to do it.
I probablly need some expression object or so.
Can anyone tell me how to solve this?
EDIT (forget the above)
This whole code is based on the quickstart in the manual (ZF2)
I have managed to write a query like this:
$select = $this->getSql()->select();
$select->columns(array(new Expression('max(id) as MaxId')));
$rowset = $this->selectWith($select);
$row = $rowset->current();
return $row;
The result of this is an empty object.
But when i change
$select->columns(array(new Expression('max(id) as MaxId')));
to
$select->columns(array(new Expression('max(id) as id')));
then i get back an object with the id as 1. Which is the max(id).
But when I add in my album object in the function exchangeArray one line with maxId, then it returns the maxId field.
BUT, it can't be that i need to do this everytime i just want to do a query like this. Is this really the way it works?
Use Zend\Db\Sql\Expression
So if i see this correctly (which may not be the case) you'd do it like you just did, but wrap the SQL-Expression into new Expression('max(id)). So it should be like the following
use Zend\Db\Sql\Expression;
//...
$this->columns(array(
'maxid' => new Expression('max(id)')
));
If the syntax like this is wrong, please don't curse me, but i would assume that knowing about the Sql\Expression will already help you ;)
Related
I'm trying to retrieve rows from a class called Consultations using a column called userPointer. It should be straight forward but I've been struggling with this for couple of days:
Let us for example say I would like to get the first object
where userPointer = ttnRYrdu0J
Note: I will replace ttnRYrdu0J with PFUser.current() later to be dynamic if this works.
I wrote the code like this:
Unfortunately it doesn't work, however when I use any other columns such as objectId or type it works fine.
Any help please!!
Thanks
I've got the answer I used PFUser.current() instead of hard coding it which is what I want at the end because I want to show the consultations of the current user and it worked! I'm still confused why it is not working when I hard code the value but I got what I want.
I have a problem which I have been trying to resolve since yesterday. I am trying to pass an SQL Query via $wpdb on wordpress but I keep getting an empty array when I try to echo the result.
I have tried print_r and var_dump and both are giving me empty values. I would appreciate if someone can help as I cannot seem to get this thing sorted.
I have also tried calling the table via the db prefix with still no success.
Below is the code I have been using
<?php
global $wpdb;
$results = $wpdb->get_results("SELECT CURRENT FROM upper_winds WHERE LVL=&level AND REGION=®ion AND VALID=&valid");
echo $results;
?>
P.S I have also tried get_var with the same problems.
Thanks
I noticed you weren't accounting for the wordpress database prefix, which could be why your results aren't showing up. You can prepend the prefix to your table name by using $wpdb->prefix.
I would suggest trying the following code:
global $wpdb;
$results = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."upper_winds WHERE LVL = 'level' AND REGION = 'region' AND VALID = 'valid'");
echo $results;
I also just wanted to point out that it's important to use $wpdb->prepare to protect against SQL Injection attacks. Any time you are writing your own SQL, you need to use $wpdb->prepare. However when you use methods like $wpdb->insert or $wpdb->update that don't require you to write any SQL, then you do not need to use $wpdb->prepare because those functions take care of SQL Escaping for you. I can't provide sample code without knowing which of your values are strings and which values are integers.
See: http://codex.wordpress.org/Class_Reference/wpdb#Protect_Queries_Against_SQL_Injection_Attacks
you need to prefix your table more than likely this is wp_ etc..
<?php
global $wpdb;
$results = $wpdb->get_results("SELECT * FROM `wp_upper_winds`
WHERE `LVL`='$level'
AND `REGION`='$region'
AND `VALID`='$valid'
");
var_dump ($results);
?>
you are looking for strings in your columns but using the &?
Thanks for your great advice and input. Eventually I got it to work.
The problem was not only in the code as I had been changing my code many times to try to find the solution. Eventually the main problem was nailed down to the table. Within one of the columns I had data which was something like this 'EU-VFR'. Apparently $wpdb did not pick up values with a '-'. Luckily with your help and some debugging I realised.
Here is what I got now http://howtoflyahelicopter.com/upper-winds-and-temp/
Thanks again :)
I want to output the query generated by a symfony propel select for testing purposes. Is there any way to do this? I know I can use the sf_debug bar, but sometimes I need to see the statement in a situation where the sf_debug bar hasn't loaded yet, or isn't going to load at all.
Timmow is right that there is a Criteria::toString() method, but it's not the magic _toString() method that's automatically called when the object is referenced as a string.
If you want to see the SQL you have to explicitly call Criteria::toString().
$c = new Criteria();
// HERE: add criteria
// what's it do?
echo $c->toString(); // oh, that's what it does
Propel Criteria objects have a toString method, so you should simply be able to echo / var_dump / log to a file the criteria object you are interested in
It also might be helpful to take a look at Day 6 of the Jobeet Tutorial, Debugging Propel generated SQL. If you're in the debug environment, the raw queries are output to the log files. Not 100% sure as I use Doctrine.
You'll get the generated SQL statement that way after you've build the criteria :
$params= array();
$resulting_sql_statement = BasePeer::createSelectSql($criteria,$params);
I'm using Symfony 1.4 and Doctrine.
Let's say I have 2 classes : a Brand and a Product.
When I create a new product in the Admin Generator based admin, I'd like to choose a brand from a dropdown list.
The Admin Generator is doing that for me, automatically creating a sfWidgetFormDoctrineChoice.
The problem is that the brands are ordered by id. I'd like them to be ordered by their "label" field.
In order to do that I did the following in my ProductForm class:
$this->widgetSchema['brand_id']->addOption('order_by','label');
But I get the following error:
Syntax error or access violation: 1064
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 'a' at line
1. Failing Query: "SELECT b.id AS b__id, b.external_id AS
b__external_id, b.label AS b__label,
b.created_at AS b__created_at,
b.updated_at AS b__updated_at FROM
brand b ORDER BY l a"
The order by statement is really weird. I don't understand why it seems to cut the name of the order by statement.
Edit: Apparently the 'order_by' option is expecting an array as a second parameter. What values does it expect?
I didn't try benlumley's solution since he answered right when I found my solution. It seems more tedious than what I ended doing.
I took a look at the source code to figure out how all this was working.
It turns out the "order_by" option needs an array specifying the field on which one wants to order the results and either 'asc' or 'desc':
$this->widgetSchema['product_id']->addOption('order_by',array('label','asc'));
It works like a charm.
You should take a look here:
http://trac.symfony-project.org/wiki/HowtoSortAdminGeneratorListByForeignTableName
Its based off of an old version of symfony, so suspect the plugin it links won't work. But I think the method should still be sound - crux of it is that you have to add method to the action to intercept and amend the default handling of sorting by this specific field:
For doctrine, you need to define/override addSortQuery, for propel, addSortCriteria.
Recommend you take a look in the cache folder to see what the auto-generated classes look like to get the hang of how it works.
Long title, I know but I searched all over and couldn't find that error message coming from that function call so I thought this might be more useful.
This is the code snippet:
string hql = " from LabRequest r where 1 = 1 ";
hql += " and 0 < (select count(rs) ";
hql += " from r.Statuses rs ";
hql += " where rs.StatusType.Description IN ('Assigned','Submitted')";
hql += " ) ";
//Session.Clear();
IQuery query = Session.CreateQuery(hql);
IQueryable<LabRequest> requests = query.List<LabRequest>().AsQueryable<LabRequest>();
This is a function (or most of it) in my Data Access Object in an MVC app I'm working on. It's for a search page and when the page runs this function gets called exactly like you see in the code and works.
Then, without changing anything, I refresh the page which goes through the same steps and calls this code, exactly as you see it, again. But the second time through it crashes on the query.List() portion of the last line with the error in the subject.
Session is defined in another DAO as:
session = NHibernateHelper.GetCurrentSession();
I know this is hard to analyze without the actual DB but I just wanted to see if anyone could maybe point me in the right direction, or maybe point out something obvious about NHibernate since I know basically nothing about it.
Edit: forgot to mention that when I uncomment the Session.Clear() it works fine, so was thinking the answer has something to do with that, and if it does how I should handle when to clear()?
Edit 2: This is part of the answer, but I call a very similar function prior to this one the second time around. What I can't figure out is why that one is affecting the one I posted. The 'query' variable is local, so it seems to be something with Session.CreateQuery. Anyone know what that would be?
Thanks,
Jeff
While I'm not sure why exactly it seems the 'Statistics' property on the Session has data on it from the first query and I think this is what's causing the error because if I do a Session.Clear it removes the collections in the Statistics property.
As my current, and possibly temporary fix, I just created an extension method for the CreateQuery function that takes a bool asking whether to clear the Session and am just using this instead of the one provided.
If anyone else has any real answer to this please add it.
Relating to your "Edit 1" and "Edit 2" notes, yes, it has to do with the session that is shared (assuming you're using one of the standard methods of handling sessions in NHibernate).
Is there a good reason for using Session.Clear()? In general, Clear is only used after a flush, to make sure the Session cache doesn't get too big causing a performance hit. Are you using it that way, or for some business reason not mentioned in your question?