get one result from a query - php

I tried doing this,
//returns the last updated id
$val = $DB->GetOne("SELECT id FROM table_name ORDER BY id DESC LIMIT 0,1");
But it doesn't work unless I do $DB->GetRow(). So, does this mean that I need to have where clause for the GetOne() to work?

I would imagine that since you are querying for one result, the WHERE clause is essential. If you attempt to get one result without defining what you are looking for, then I don't imagine it will work in the way you intend. Refer to the PHP Code Examples from the ADOdb documentation.

The code in the question will work but there was a bug in the adodb mysql driver where it will return false (instead of NULL) when no results are found. The bug was fixed in 2010 . So you may be experiencing the bug if you're running an old version of adodb.
GetOne returns the content of the first field in the first row of the result set.
Also saying "it's not working" doesn't say much.
Try printing $DB->ErrorMsg() to see what's wrong.

Related

SQL LIMIT VS Loop Limit

I was browsing around Stack Overflow attempting to find how to limit an SQL query with a while loop and I came across this code.
$count = 0;
while ($count < 4 && $info = mysql_fetch_assoc($result)) {
//stuff
$count++;
}
Q 1: What is the difference between this code and using the SQL LIMIT clause?
Q 2: For what reason would somebody want to use this code, rather than using LIMIT?
With this code, the MySQL server will send all the results to the client, but the client ignores everything after the 4th row. So the server has to do more work, and more bandwidth will be used between the client and server.
They might want to use mysql_num_rows() to find out how many total rows were selected, even though they only want to display the first 4. However, MySQL provides a way to do that with LIMIT -- you can put the SQL_CALC_FOUND_ROWS option in the SELECT clause, and then use SELECT FOUND_ROWS() to get the total number of rows. So there's no good reason, except they don't know about this feature.
Everyting #Barmar said is right on. Following with code like that will cause lots of problems as your result sets start to grow. Let a database do what its good at doing, let it supply the limit of results you want/need. Just think of what happens when you do a SELECT with no LIMIT clause in the command line client where there are thousands of rows...it just goes on and on.
One more thing, I wouldn't recommend using mysql_num_rows() as its a deprecated function. Might as well go along with mysqli or PDO.

PHPMYADMIN returns result, PHP Query doesnt

So, I created a query in PhpMyAdmin to pick one random online member that is part of a certain group. It works fine in PhpMyAdmin and does exactly what I want. However, when I run this query using PHP it does not return anything. I simply get 'NULL' when I use var_dump($result).
$sql= "SELECT
ow_base_user_online.userId,
ow_base_authorization_user_role.roleId
FROM
ow_base_user_online
INNER JOIN ow_base_authorization_user_role ON ow_base_authorization_user_role.userId = ow_base_user_online.userId
WHERE
ow_base_authorization_user_role.roleId = 14
ORDER BY
RAND()
LIMIT 1";
$result = OW::getDbo()->queryForList($sql);
Please, does anyone have any ideas?
Please does anyone have any ideas?
Yes, use error reporting from your mysql query and see what it returns. Check PHP errors too (can get auth warnings to show something daft like bad user/password etc).
Also, for testing, try removing the class you use and stick the DB connection code above that query and query all direct from a test script. If it works fine, then your query is ok, as is the connection and credentials.
From there you can work backwards checking the class you have.

MySQL fulltext index search mysql_num_rows returns 1

Correction below!
I search a fairly large table for matches with this simple SQL question:
$result = mysql_query("SELECT *, MATCH(foretag, stad) AGAINST('$query') AS r FROM tblforetag WHERE MATCH(foretag, stad) AGAINST('$query')");
...but mysql_num_rows($result) always returns 1.
I tried the exact same query (with the same value as $query) in HeidiSQL and it returned 45 results.
Any clues how to get rid of this problem?
Correction: As it turns out, the counting isn't the problem. This only returns one result on the PHP page, but not when executed directly in an MySQL prompt or in HeidiSQL (essentially the same thing).
The problem was the encoding. I just realized this since I got a match on "ping". I solved this issue by using utf8_decode().

MySQL - Simple search for ID and return name

G'day,
I'm not familiar with MySQL and this will probably be an easy question!
I am trying to mod a Joomla plugin and am working with this code that works well for a similar function:
$q="SELECT `".$naming."` AS naming FROM `#__users` WHERE `id`='".$jomsocial_event->creator."' ";
$db->setQuery($q);
$eventcreatorname = $db->loadResult();
$eventcreator = ''.addslashes($eventcreatorname).'';
What I need to do is lookup the field id in the table community_groups and return the matching field name. What I have is (note that $jomsocial_event->contentid contains the group ID):
$q="SELECT `".$naming."` AS naming FROM `#__community_groups` WHERE `id`='".$jomsocial_event->contentid."' ";
$db->setQuery($q);
$eventgroupname = $db->loadResult();
$eventgroup = ''.addslashes($eventcreatorname).'';
It returns nothing as the query is wrong; what should it be for my usage?
I'd work backwards from the database.
i.e. turn on SQL logging and look at what's actually arriving in the database. Tweak as necessary by playing with the resulting SQL until you get what you want (and expect) and then implement that in your code.
Take a look at your generated query in the debugging from Joomla.
Run it against mysql directly and see where it goes wrong.
Also, I'd use the JDatabaseQuery API because you are much less likely to get errors with quoting etc. It looks to me like you are treating id as a string not an integer.

Get Number of Rows from a Select Statement Efficiently

Until recently I've been using mysql_real_escape_string() to fix most of my variables before making SQL queries to my database. A friend said that I should be using PDO's prepared statements instead, so after reading a bit about them I'm now switching over to them.
I've only encountered one problem so far in switching over, and that's counting the rows to returned by a SELECT statement. On occasion in my code, I'd run an SQL query and then count the number of rows returned from the SELECT statement. Depending on whether a result set returned, I would take different actions. Sometimes I do need to use the result set from it. MySQL let me go straight to mysql_fetch_assoc() after mysql_num_rows() with no problem. However, PDO doesn't seem to have anything like mysql_num_rows().
I've been reading some responses on SO that gave me a solution, to either use COUNT() in the SQL statement or to use the PHP function count() on the result set. COUNT() would work fine in the SQL statement if I didn't need the result set in some places, however, several people have mentioned that using count() on the result set is fairly inefficient.
So my question is, how should I be doing this if I need to count the number of rows selected (if any), then run a script with the result set? Is using count() on the result set the only way in this case, or is there a more efficient way to do things?
Below is a short example of something similar to my previous SQL code:
$query=mysql_query('SELECT ID FROM Table WHERE Name='Paul' LIMIT 1);
if(mysql_num_rows($query)>0)
{
print_r(mysql_fetch_assoc($query));
}
else
{
//Other code.
}
Thanks.
EDIT
I do know that you use fetchAll() on the statement before counting the result set (which gives me what I need), but I'm just trying to figure out the most efficient way to do things.
$stmt->rowCount();
http://php.net/manual/en/pdostatement.rowcount.php
the rows must be fetched(buffered into memory, or iterated) for it to work. It's not uncommon for your pdo driver to be configured to do this automatically.
You will have to use Count(). You can run two queries like
SELECT COUNT(ID) FROM Table WHERE Name='Paul'
one you have get the count, then run the query with select clause
SELECT ID FROM Table WHERE Name='Paul' LIMIT 1
Count() function is not inefficient at all if you are using it like COUNT(ID), because most probably id is primary key and have an index. MYSQL wont even have to access the table.

Categories