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 :)
Related
LuaSQL, which seems to be the canonical library for most SQL database systems in Lua, doesn't seem to have any facilities for quoting/escaping values in queries. I'm writing an application that uses SQLite as a backend, and I'd love to use an interface like the one specified by Python's DB-API:
c.execute('select * from stocks where symbol=?', t)
but I'd even settle for something even dumber, like:
conn:execute("select * from stocks where symbol=" + luasql.sqlite.quote(t))
Are there any other Lua libraries that support quoting for SQLite? (LuaSQLite3 doesn't seem to.) Or am I missing something about LuaSQL? I'm worried about rolling my own solution (with regexes or something) and getting it wrong. Should I just write a wrapper for sqlite3_snprintf?
I haven't looked at LuaSQL in a while but last time I checked it didn't support it. I use Lua-Sqlite3.
require("sqlite3")
db = sqlite3.open_memory()
db:exec[[ CREATE TABLE tbl( first_name TEXT, last_name TEXT ); ]]
stmt = db:prepare[[ INSERT INTO tbl(first_name, last_name) VALUES(:first_name, :last_name) ]]
stmt:bind({first_name="hawkeye", last_name="pierce"}):exec()
stmt:bind({first_name="henry", last_name="blake"}):exec()
for r in db:rows("SELECT * FROM tbl") do
print(r.first_name,r.last_name)
end
LuaSQLite3 as well an any other low level binding to SQLite offers prepared statements with variable parameters; these use methods to bind values to the statement parameters. Since SQLite does not interpret the binding values, there is simply no possibility of an SQL injection. This is by far the safest (and best performing) approach.
uroc shows an example of using the bind methods with prepared statements.
By the way in Lua SQL there is an undocumented escape function for the sqlite3 driver in conn:escape where conn is a connection variable.
For example with the code
print ("con:escape works. test'test = "..con:escape("test'test"))
the result is:
con:escape works. test'test = test''test
I actually tried that to see what it'd do. Apparently there is also such a function for their postgres driver too. I found this by looking at the tests they had.
Hope this helps.
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 ;)
Is librdf_model_add writing the statements into the hash-storage?
I am having problem to run a sparql query to retrieve them. The db files are probably populated as their file size keep increasing, but when I attempt to perform sparql query to them I don't seem to get any result. Do I need to load the statements from the storage into the model manually before issuing a query?
the statement that issue the query
$query = librdf_new_query(
$world,
'sparql',
NULL,
<<<SPARQL
PREFIX sensei: <http://coolsilon.com/flickr_schema/>
SELECT ?a ?c
WHERE {?a ?b ?c}
SPARQL
,
NULL
);
$result = librdf_query_execute($query, $model);
var_dump(librdf_query_results_get_count($result)); // returns 0
I am using PHP (5.3.5) language binding, and my redland version is 1.0.12 running under Ubuntu Natty.
p/s: I checked again with postgresql storage, and the above code works :/
This is better asked on semantic overflow or the redland-dev list.
The most likely thing is the model has no data.
Use some of the librdf functions to print out the model or use a serializer.
Try the test.php for pointers in https://github.com/dajobe/redland-bindings/tree/master/php
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);
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?