JPQL: MySQL-like LIMIT-clause

hi
i was wondering if i could possibly limit a JPQL result list in the way that it only contains a specified number of rows starting at a certain offset.
for example, in MySQL i could simply use LIMIT like this:
SELECT * FROM example ORDER BY c1 LIMIT 20, 10
and it would return 10 rows starting at 20th row instead of the whole realtion.
any help will be appreciated

The preferred solution is to make use of the analytic function ROW_NUMBER. There is a description in the Oracle documentation. The final example shown returns only the fifty-first through one-hundredth row of the EMPLOYEES table:
SELECT last_name FROM
   (SELECT last_name, ROW_NUMBER() OVER (ORDER BY last_name) R FROM employees)
   WHERE R BETWEEN 51 and 100;An alternative is to use:
    select *
      from ( select a.*, rownum rnum
            from ( YOUR_QUERY_GOES_HERE -- including the order by ) a
           where rownum <= MAX_ROWS )
     where rnum >= MIN_ROWS;which is discussed on asktom.oracle.com. This works from Oracle 8.1 onwards.
-- cj

Similar Messages

  • MySQL LIMIT clause equivalent in ORACLE statement

    Is there an Oracle SQL statement that would be equivalent to the MySQL LIMIT clause used to return only part of a result set?

    The preferred solution is to make use of the analytic function ROW_NUMBER. There is a description in the Oracle documentation. The final example shown returns only the fifty-first through one-hundredth row of the EMPLOYEES table:
    SELECT last_name FROM
       (SELECT last_name, ROW_NUMBER() OVER (ORDER BY last_name) R FROM employees)
       WHERE R BETWEEN 51 and 100;An alternative is to use:
        select *
          from ( select a.*, rownum rnum
                from ( YOUR_QUERY_GOES_HERE -- including the order by ) a
               where rownum <= MAX_ROWS )
         where rnum >= MIN_ROWS;which is discussed on asktom.oracle.com. This works from Oracle 8.1 onwards.
    -- cj

  • Simple LIMIT Clause Impossible?

    Is the simple LIMIT clause available in other databases simply impossible in Oracle? This is driving me nuts and I'm just not finding a good answer.
    For example, the query:
    SELECT * FROM MYUSER ORDER BY LOGIN LIMIT 41, 20
    This would return up to 20 rows starting at row 41 in the query.
    How is this done in Oracle?
    I've seen ROWNUM, but:
    SELECT * FROM MYUSER ORDER BY LOGIN WHERE ROWNUM > 40 AND ROWNUM < 61
    This won't work because ROWNUM > x is not valid and will always return nothing. Also the ORDER BY is done after the where, so you wouldn't get the right rows anyway.
    You can fix the ORDER BY problem with:
    SELECT * FROM MYUSER (SELECT LOGIN FROM MYUSER ORDER BY LOGIN) WHERE ROWNUM > 40 AND ROWNUM < 61
    But you still have the ROWNUM > x is invalid problem.
    This seems just as silly as Oracle's NULL == '' problem. But anyway...
    Let me explain why I need this and maybe someone can tell me what I can do as a workaround.
    I have a web application that (among many other things) has a table of users. This table can easily reach into the tens of thousands of entries.
    The web application allows the administrator to page through the list of users, sorting by different criteria, so that they can locate a particular user, group of users, or just so they can generally browse things.
    I attempt to keep as little stateful information as possible so that memory (and other resources) aren't wasted.
    When a user clicks on the list of users, I do a query for the first 20 rows and display them, sorted by whatever criteria the user sets. The user can then hit the "next page" link and I do another query for rows 21-40 and display those. And so on, both forward and backward, with an option to go to the first 20 and the last 20.
    I'm doing all this through Java and JDBC on a proprietary web server that supports Java servlets.
    I could keep a result set open and that would help with page forwards (just grab the next 20 from the set). But what about paging backward? Or jumping ahead to the end? Or jumping ahead or backward several pages?
    This seems like a very common web application theme. What am I missing?
    Greg
    null

    To answer your last question ('What am I missing?') first - you aren't missing anything.
    You are correct - this is a very common question. You will find a dozen or more similar questions if you search this forum (search on ROWNUM).
    Oracle assigns ROWNUM as the result set records are being retrieved. Naturally this is before the ORDER BY clause since Oracle can't order what doesn't exist.
    That is why 'ROWNUM <' works (oracle quits when the desired number of rows is reached) but 'ROWNUM >' does not work (ROWNUM will never get to the desired number).
    The trick is to use a nested query or multiple nested queries. Oracle 8i supports the ORDER BY clause in nested queries.
    The first (innermost) query selects records and orders them.
    The second query is used to wrap the first query and assign row numbers.
    The third query selects the desired range of rows from the second query.
    'select * from (select rownum rn, e.* from
    (select * from emp order by ename desc) e) where rn >= 4'
    If an ORDER BY is not needed you can eliminate the first query.
    'select * from (select rownum rn, e.* from emp e) where rn >= 4'
    The inner query creates the RN column based on ROWNUM and the outer query uses the RN column (just as if it existed in a table) to select records with an RN value >= 4.
    Keep in mind that the performance will go down as the number of records goes up.
    For best results you need have a column in the table that you can use in the WHERE clause. Unfortunately this isn't always possible if you are trying to support generic ORDER BY clauses.
    One way that is often useful to try to understand why things like this 'are the way they are' is to examine how you would perform the task manually.
    Suppose I place in front of you a stack of 8 1/2 X 11 paper whose pages are not numbered and ask you to find and make copies of pages 40 - 60.
    How would you do it? You would start counting from the beginning. When you reach page 40 you would copy the next 20 pages.
    When you are done the pile of paper is in exactly the same state as when you started.
    Now I ask you to give me copies of pages 61 to 80.
    You have to start all over at the beginning as if the first request never happened.
    That's pretty much what the computer has to do.
    If the pages are numbered you can go directly to the desired pages.
    Now what if I ask you to copy pages 20 to 30 after you sort them in order by LAST NAME?
    There are exceptions (e.g. parallel processing, neural networks) but generally the computer can only do what you can do yourself. It can just do it faster and more efficiently.
    Certain types of problems are not well-suited for the computer and some problems cannot be solved at all.
    null

  • LIMIT clause

    When I used MS Access with sql language I remender that for limiting retrieved records of a query I could use:
    SELECT TOP 1 * from TABLE_NAME
    So I searched for a similar clause for oracle queries and someone pointed me the LIMIT clause.
    Could anyone gimme an example on how to use it?

    The rownum usage can answered to the OP question, depend of what exactly he wants... but like below seems a little better :
    SCOTT@demo102> select empno, ename, sal, deptno from emp;
         EMPNO ENAME             SAL     DEPTNO
          7369 SMITH            8000         20
          7499 ALLEN           16000         30
          7521 WARD            12500         30
          7566 JONES           29750         20
          7654 MARTIN          12500         30
          7698 BLAKE           28500         30
          7782 CLARK           24500         10
          7788 SCOTT           30000         20
          7839 KING            50000         10
          7844 TURNER          15000         30
          7876 ADAMS           11000         20
          7900 JAMES            9500         30
          7902 FORD            30000         20
          7934 MILLER          13000         10
    14 rows selected.
    SCOTT@demo102> select empno, ename, sal, deptno
      2            from (select empno, ename, sal, deptno from emp order by sal desc)
      3            where rownum <=5;
         EMPNO ENAME             SAL     DEPTNO
          7839 KING            50000         10
          7788 SCOTT           30000         20
          7902 FORD            30000         20
          7566 JONES           29750         20
          7698 BLAKE           28500         30
    SCOTT@demo102> Anyway, like I said in the link given earlier, there is rank, dense_rank which can help for different requirements.
    Nicolas.

  • Jet OLEDB 'LIMIT' clause

    Hi Folks,
    I'm monitoring an access database for new records using LV2009 + the Database connectivity toolset(not 8.5.1 as in sig). Anyway the number of rows could be on the order of 200,000+, so I want to limit my query to only one record, the last. Unable to get the LIMIT clause to function, I searched and came across this: http://office.microsoft.com/en-us/access/HP010322501033.aspx. It states:
    Microsoft Jet SQL does not support the following ANSI SQL features:
    DISTINCT aggregate function references. For example, Microsoft Jet SQL does not allow SUM(DISTINCT columnname).
    The LIMIT TO nn ROWS clause used to limit the number of rows returned by a query. You can use only the WHERE Clause to limit the scope of a query.
    Is this the problem I'm going up against? The reason I use Jet is because I can more easily programatically load individual databases (and not have to mess around with UDL files).
    Any thoughts on a work-around?
    Happy Wiring,
    Jamie
    v2009 devel. w/RT
    Attachments:
    DB-test.zip ‏27 KB

    Potential workaround: may not be the most efficient solution though (my only exp. w/database access is from PHP/mySQL many years back!). Comments welcome. :-)
    v2009 devel. w/RT
    Attachments:
    DB-access-TEST_v2.vi ‏25 KB

  • Facebook Page Like Limit

    Does anyone know what the Like limit is on a single Facebook page before having to pay Facebook? I cannot seem to find a straight answer on this. Sorry if this is the wrong forum for this.
    This topic first appeared in the Spiceworks Community

    Does anyone know what the Like limit is on a single Facebook page before having to pay Facebook? I cannot seem to find a straight answer on this. Sorry if this is the wrong forum for this.
    This topic first appeared in the Spiceworks Community

  • Can you include feature like LIMIT in Mysql next release

    Hi,
    It brings me trouble in code design when using query:
    SELECT col FROM (SELECT col, ROWNUM r FROM table ORDER BY ord) WHERE r BETWEEN 10 AND 20.
    In most of other databases, such query can be done much easier, eg:
    SELECT col FROM table WHERE cond ORDER BY ord LIMIT 10, 20
    I think this is a "nice to have" feature in Oracle.
    Sean

    I need to specify the results are from row 10 to row 20As I said above, without any order by clause, there is no sens to get the rows from 10 to 20 (10th to 20th on which criteria ?).
    So, when you will choose a criteria, you will able to get the rows from 10 to 20, for example :
    SQL> select username, created, row_number() over (order by created) rn from all_users order by 2;
    USERNAME                       CREATED          RN
    SYS                            14/11/05          1
    SYSTEM                         14/11/05          2
    OUTLN                          14/11/05          3
    DBSNMP                         14/11/05          4
    PS                             14/11/05          5
    H89UCBAC                       14/11/05          6
    PEOPLE                         14/11/05          7
    ONE                            06/07/06          8
    TITI                           11/07/06          9
    TOTO                           31/08/06         10
    TATA                           21/09/06         11
    11 rows selected.
    SQL> select username, created
      2  from (select username, created, row_number() over (order by created) rn from all_users)
      3  where rn between 5 and 8;
    USERNAME                       CREATED
    PS                             14/11/05
    H89UCBAC                       14/11/05
    PEOPLE                         14/11/05
    ONE                            06/07/06
    SQL> Wheck the doc for row_number, rank and dense_rank to see the differences between these ones. Depend of what exactly you want.
    Nicolas.

  • MySQL LIKE Function Not Working

    I've got a really weird situation here. I'm building a
    dynamic query to a MySQL database that uses the like operator in
    the WHERE clause. It seems that for whatever reason, the LIKE part
    isn't working. Here's the query:
    SELECT DISTINCT model, makeID, engineID, partnum_oem,
    partnum_goodyear, partnum_tendeco, partnum_gates, app_desc,
    app_type, app_comment
    FROM part
    WHERE (year = '#attributes.year#')
    <cfif attributes.make NEQ "">AND (makeID LIKE
    '%#attributes.make#%')</cfif>
    <cfif thisModel NEQ "">
    AND (model LIKE '%#TRIM(ReplaceNoCase(thisModel, "|", "%' OR
    model LIKE '%", "ALL"))#%')
    </cfif>
    <cfif thisEngine NEQ "">
    AND (engineID LIKE '%#TRIM(ReplaceNoCase(thisEngine, "|",
    "%' OR engineID LIKE '%", "ALL"))#%')
    </cfif>
    ORDER BY makeID, model
    I turned on the debug output and here is the query it is
    passing:
    SELECT DISTINCT model, makeID, engineID, partnum_oem,
    partnum_goodyear, partnum_tendeco, partnum_gates, app_desc,
    app_type, app_comment FROM part WHERE (year = '2006') AND (makeID
    LIKE '%Sterling%') AND (model LIKE '%L9500 Series%' OR model LIKE
    '%L-Line%') AND (engineID LIKE '%Detroit Diesel Series 60 Diesel%')
    ORDER BY makeID, model
    Now, If I paste this query into NaviCat, it works perfectly
    and returns the 3 expected results. If I replace the dynamic query
    in the CF code with the static query, it works fine and gives me 3
    results. However, when built dynamically, I get 0 results. Also
    weird is that the values of the above query are exact matches for
    what's in the DB (the LIKE part shouldn't even come into play!) and
    still no results.
    This is all run inside a custom tag, but I can see the
    results directly through debug. I've used LIKE many times without
    issue before, and obviously the query is right since it works when
    hard-coded.
    We are using CF 7.0.2 on Windows 2003 and MySQL 5.0 with the
    J-Connector driver. I also tried this same code to the same data on
    a MySQL 4.1 database using the CF built in driver for MySQL and got
    the same result.
    Anybody have any ideas?

    I've never used REQUEST, but from what I understand it's just a generic way of saying $_GET or $_POST. Here a note from http://php.benscom.com/manual/en/reserved.variables.request.php
    "Note: The variables in $_REQUEST are provided to the script via the GET, POST, and COOKIE input mechanisms and therefore could be modified by the remote user and cannot be trusted. The presence and order of variables listed in this array is defined according to the PHP variables_order configuration directive. "
    Rule of thumb is if you are retrieving any data from an external source such as a form or $_GET, you should assume that the data might not be as you expect it. Hackers can manipulate data sent to your website to gain access to your database. So, never trust it.
    e.g if you have a name field, and some ones name is O'Reily and your insert statement looks like this - 'INSERT INTO ....'  the ' between O & Reily would mess up your query as it will assume that ' marks the end of the query. Therefore you need to use a function called addslashes to the posted variable:
    e.g
    $name = addslashes($_POST['name']); // outputs O\'Reily
    there are many ways to clean your data, I always write a function to clean $_GET & $_POST.
    e.g $name = clean_data($_POST['name'];  where clean_data processes the data and returns a sanitised version.
    do a google search for 'php sanitize/sanitise data', there are thousands of simple solutions to protecting your data.
    Chris

  • Cm:select performance problem with multiple likes query clause

    I have query like <br>
              <b>listItem like '*abc.xml*' && serviceId like '*xyz.xml*'</b><br>
              Can we have two likes clauses mentioned above in the cm:select. The above is executing successfully but takes too much time to process. <br><br>
              Can we simplify the above mentioned query or any solution. Please help me in this issue.<br><br>
              Thanks & Regards,<br>
              Murthy Nalluri

    A few notes:
    1. You seem to have either a VPD policy active or you're using views that add some more predicates to the query, according to the plan posted (the access on the PK_OPERATOR_GROUP index). Could this make any difference?
    2. The estimates of the optimizer are really very accurate - actually astonishing - compared to the tkprof output, so the optimizer seems to have a very good picture of the cardinalities and therefore the plan should be reasonable.
    3. Did you gather index statistics as well (using COMPUTE STATISTICS when creating the index or "cascade=>true" option) when gathering the statistics? I assume you're on 9i, not 10g according to the plan and tkprof output.
    4. Looking at the amount of data that needs to be processed it is unlikely that this query takes only 3 seconds, the 20 seconds seems to be OK.
    If you are sure that for a similar amount of underlying data the query took only 3 seconds in the past it would be very useful if you - by any chance - have an execution plan at hand of that "3 seconds" execution.
    One thing that I could imagine is that due to the monthly data growth that you've mentioned one or more of the tables have exceeded the "2% of the buffer cache" threshold and therefore are no longer treated as "small tables" in the buffer cache. This could explain that you now have more physical reads than in the past and therefore the query takes longer to execute than before.
    I think that this query could only be executed in 3 seconds if it is somewhere using a predicate that is more selective and could benefit from an indexed access path.
    Regards,
    Randolf
    Oracle related stuff blog:
    http://oracle-randolf.blogspot.com/
    SQLTools++ for Oracle (Open source Oracle GUI for Windows):
    http://www.sqltools-plusplus.org:7676/
    http://sourceforge.net/projects/sqlt-pp/

  • How to create Mysql like table with LinkedList or LinkedHashMap

    Is it possible to create a class which can create tables like Mysql tables? Take the following table as an example,
    0, LastName0, FirstNam0, Ag0, Phon0
    1, LastName1, FirstNam1, Ag1, Phon1
    2, LastName2, FirstNam2, Ag2, Phon2
    It's very easy to create a table in MySql with the following data. Now what if I want to create a table in the memory, so I can retrieve or SORT it whichever way I want. I might want to sort it by lastname or by phone number.
    Is it possible to do that with LinkedList or LinkedHashMap?

    1. Create a class with the fields lastName, firstName, age, phone of appropriate types
    2. Create objects of this and put in some type of a collections (ArrayList, Vector)
    3. Sort it using Collections.sort. Use a Comparator that compares the fields of interest

  • Is the new ipod 5th gen yellow ipod really yellow it looks like lime green?

    Is the new ipod yellow or lime green, the color just looks different?

    Visit an Apple store or other store that has them and look. It is kind of subjective otherwise.

  • Like clause in PreparedStatement not working

    Hi
    I need to create a PreparedStatement that selects using a like where clause. I do the following:
    String param0 = "ABC%";
    PreparedStatement pstmt = conn.prepareStatement("select ISSUEID from DMFI_ISSUE where ISIN like ?");
    setObject(pstmt,1,param0,java.sql.Types.VARCHAR);
    This doesn't work. If param0 is set to the exact value in the database (e.g. "ABCDEF") it selects one, but the like is not working. Is this a jdbc bug? I need to use a PreparedStatement.
    Can anyone help?
    Thanks

    Please ignore, mea culpa, just a vagary of the dos shell. I passed in "abc%" from the dos prompt.

  • How can I modify this script to return only certain rows of my mySQL table?

    Hi there,
    I have a php script that accesses a mySQL database and it was generated out of the Flex Builder wizard automatically. The script works great and there are no problems with it. It allows me to perform CRUD on a table by calling it from my Flex app. and it retrieves all the data and puts it into a nice MXML format.
    My question, currently when I call "findAll" to retrieve all the data in the table, well, it retrieves ALL the rows in the table. That's fine, but my table is starting to grow really large with thousands of rows.
    I want to modify this script so that I can pass a variable into it from Flex so that it only retrieves the rows that match the "$subscriber_id" variable that I pass. In this way the results are not the entire table's data, only the rows that match 'subscriber_id'.
    I know how to pass a variable from Flex into php and the code on the php side to pick it up would look like this:
    $subscriberID = $_POST['subscriberID'];
    Can anyone shed light as to the proper code modification in "findAll" which will take my $subscriberID variable and compare it to the 'subscriber_id' field and then only return those rows that match? I think it has something to do with lines 98 to 101.
    Any help is appreciated.
    <?php
    require_once(dirname(__FILE__) . "/2257safeDBconn.php");
    require_once(dirname(__FILE__) . "/functions.inc.php");
    require_once(dirname(__FILE__) . "/XmlSerializer.class.php");
    * This is the main PHP file that process the HTTP parameters,
    * performs the basic db operations (FIND, INSERT, UPDATE, DELETE)
    * and then serialize the response in an XML format.
    * XmlSerializer uses a PEAR xml parser to generate an xml response.
    * this takes a php array and generates an xml according to the following rules:
    * - the root tag name is called "response"
    * - if the current value is a hash, generate a tagname with the key value, recurse inside
    * - if the current value is an array, generated tags with the default value "row"
    * for example, we have the following array:
    * $arr = array(
    *      "data" => array(
    *           array("id_pol" => 1, "name_pol" => "name 1"),
    *           array("id_pol" => 2, "name_pol" => "name 2")
    *      "metadata" => array(
    *           "pageNum" => 1,
    *           "totalRows" => 345
    * we will get an xml of the following form
    * <?xml version="1.0" encoding="ISO-8859-1"?>
    * <response>
    *   <data>
    *     <row>
    *       <id_pol>1</id_pol>
    *       <name_pol>name 1</name_pol>
    *     </row>
    *     <row>
    *       <id_pol>2</id_pol>
    *       <name_pol>name 2</name_pol>
    *     </row>
    *   </data>
    *   <metadata>
    *     <totalRows>345</totalRows>
    *     <pageNum>1</pageNum>
    *   </metadata>
    * </response>
    * Please notice that the generated server side code does not have any
    * specific authentication mechanism in place.
    * The filter field. This is the only field that we will do filtering after.
    $filter_field = "subscriber_id";
    * we need to escape the value, so we need to know what it is
    * possible values: text, long, int, double, date, defined
    $filter_type = "text";
    * constructs and executes a sql select query against the selected database
    * can take the following parameters:
    * $_REQUEST["orderField"] - the field by which we do the ordering. MUST appear inside $fields.
    * $_REQUEST["orderValue"] - ASC or DESC. If neither, the default value is ASC
    * $_REQUEST["filter"] - the filter value
    * $_REQUEST["pageNum"] - the page index
    * $_REQUEST["pageSize"] - the page size (number of rows to return)
    * if neither pageNum and pageSize appear, we do a full select, no limit
    * returns : an array of the form
    * array (
    *           data => array(
    *                array('field1' => "value1", "field2" => "value2")
    *           metadata => array(
    *                "pageNum" => page_index,
    *                "totalRows" => number_of_rows
    function findAll() {
         global $conn, $filter_field, $filter_type;
          * the list of fields in the table. We need this to check that the sent value for the ordering is indeed correct.
         $fields = array('id','subscriber_id','lastName','firstName','birthdate','gender');
         $where = "";
         if (@$_REQUEST['filter'] != "") {
              $where = "WHERE " . $filter_field . " LIKE " . GetSQLValueStringForSelect(@$_REQUEST["filter"], $filter_type);     
         $order = "";
         if (@$_REQUEST["orderField"] != "" && in_array(@$_REQUEST["orderField"], $fields)) {
              $order = "ORDER BY " . @$_REQUEST["orderField"] . " " . (in_array(@$_REQUEST["orderDirection"], array("ASC", "DESC")) ? @$_REQUEST["orderDirection"] : "ASC");
         //calculate the number of rows in this table
         $rscount = mysql_query("SELECT count(*) AS cnt FROM `modelName` $where");
         $row_rscount = mysql_fetch_assoc($rscount);
         $totalrows = (int) $row_rscount["cnt"];
         //get the page number, and the page size
         $pageNum = (int)@$_REQUEST["pageNum"];
         $pageSize = (int)@$_REQUEST["pageSize"];
         //calculate the start row for the limit clause
         $start = $pageNum * $pageSize;
         //construct the query, using the where and order condition
         $query_recordset = "SELECT id,subscriber_id,lastName,firstName,birthdate,gender FROM `modelName` $where $order";
         //if we use pagination, add the limit clause
         if ($pageNum >= 0 && $pageSize > 0) {     
              $query_recordset = sprintf("%s LIMIT %d, %d", $query_recordset, $start, $pageSize);
         $recordset = mysql_query($query_recordset, $conn);
         //if we have rows in the table, loop through them and fill the array
         $toret = array();
         while ($row_recordset = mysql_fetch_assoc($recordset)) {
              array_push($toret, $row_recordset);
         //create the standard response structure
         $toret = array(
              "data" => $toret,
              "metadata" => array (
                   "totalRows" => $totalrows,
                   "pageNum" => $pageNum
         return $toret;
    * constructs and executes a sql count query against the selected database
    * can take the following parameters:
    * $_REQUEST["filter"] - the filter value
    * returns : an array of the form
    * array (
    *           data => number_of_rows,
    *           metadata => array()
    function rowCount() {
         global $conn, $filter_field, $filter_type;
         $where = "";
         if (@$_REQUEST['filter'] != "") {
              $where = "WHERE " . $filter_field . " LIKE " . GetSQLValueStringForSelect(@$_REQUEST["filter"], $filter_type);     
         //calculate the number of rows in this table
         $rscount = mysql_query("SELECT count(*) AS cnt FROM `modelName` $where");
         $row_rscount = mysql_fetch_assoc($rscount);
         $totalrows = (int) $row_rscount["cnt"];
         //create the standard response structure
         $toret = array(
              "data" => $totalrows,
              "metadata" => array()
         return $toret;

    Hi there,
    I have a php script that accesses a mySQL database and it was generated out of the Flex Builder wizard automatically. The script works great and there are no problems with it. It allows me to perform CRUD on a table by calling it from my Flex app. and it retrieves all the data and puts it into a nice MXML format.
    My question, currently when I call "findAll" to retrieve all the data in the table, well, it retrieves ALL the rows in the table. That's fine, but my table is starting to grow really large with thousands of rows.
    I want to modify this script so that I can pass a variable into it from Flex so that it only retrieves the rows that match the "$subscriber_id" variable that I pass. In this way the results are not the entire table's data, only the rows that match 'subscriber_id'.
    I know how to pass a variable from Flex into php and the code on the php side to pick it up would look like this:
    $subscriberID = $_POST['subscriberID'];
    Can anyone shed light as to the proper code modification in "findAll" which will take my $subscriberID variable and compare it to the 'subscriber_id' field and then only return those rows that match? I think it has something to do with lines 98 to 101.
    Any help is appreciated.
    <?php
    require_once(dirname(__FILE__) . "/2257safeDBconn.php");
    require_once(dirname(__FILE__) . "/functions.inc.php");
    require_once(dirname(__FILE__) . "/XmlSerializer.class.php");
    * This is the main PHP file that process the HTTP parameters,
    * performs the basic db operations (FIND, INSERT, UPDATE, DELETE)
    * and then serialize the response in an XML format.
    * XmlSerializer uses a PEAR xml parser to generate an xml response.
    * this takes a php array and generates an xml according to the following rules:
    * - the root tag name is called "response"
    * - if the current value is a hash, generate a tagname with the key value, recurse inside
    * - if the current value is an array, generated tags with the default value "row"
    * for example, we have the following array:
    * $arr = array(
    *      "data" => array(
    *           array("id_pol" => 1, "name_pol" => "name 1"),
    *           array("id_pol" => 2, "name_pol" => "name 2")
    *      "metadata" => array(
    *           "pageNum" => 1,
    *           "totalRows" => 345
    * we will get an xml of the following form
    * <?xml version="1.0" encoding="ISO-8859-1"?>
    * <response>
    *   <data>
    *     <row>
    *       <id_pol>1</id_pol>
    *       <name_pol>name 1</name_pol>
    *     </row>
    *     <row>
    *       <id_pol>2</id_pol>
    *       <name_pol>name 2</name_pol>
    *     </row>
    *   </data>
    *   <metadata>
    *     <totalRows>345</totalRows>
    *     <pageNum>1</pageNum>
    *   </metadata>
    * </response>
    * Please notice that the generated server side code does not have any
    * specific authentication mechanism in place.
    * The filter field. This is the only field that we will do filtering after.
    $filter_field = "subscriber_id";
    * we need to escape the value, so we need to know what it is
    * possible values: text, long, int, double, date, defined
    $filter_type = "text";
    * constructs and executes a sql select query against the selected database
    * can take the following parameters:
    * $_REQUEST["orderField"] - the field by which we do the ordering. MUST appear inside $fields.
    * $_REQUEST["orderValue"] - ASC or DESC. If neither, the default value is ASC
    * $_REQUEST["filter"] - the filter value
    * $_REQUEST["pageNum"] - the page index
    * $_REQUEST["pageSize"] - the page size (number of rows to return)
    * if neither pageNum and pageSize appear, we do a full select, no limit
    * returns : an array of the form
    * array (
    *           data => array(
    *                array('field1' => "value1", "field2" => "value2")
    *           metadata => array(
    *                "pageNum" => page_index,
    *                "totalRows" => number_of_rows
    function findAll() {
         global $conn, $filter_field, $filter_type;
          * the list of fields in the table. We need this to check that the sent value for the ordering is indeed correct.
         $fields = array('id','subscriber_id','lastName','firstName','birthdate','gender');
         $where = "";
         if (@$_REQUEST['filter'] != "") {
              $where = "WHERE " . $filter_field . " LIKE " . GetSQLValueStringForSelect(@$_REQUEST["filter"], $filter_type);     
         $order = "";
         if (@$_REQUEST["orderField"] != "" && in_array(@$_REQUEST["orderField"], $fields)) {
              $order = "ORDER BY " . @$_REQUEST["orderField"] . " " . (in_array(@$_REQUEST["orderDirection"], array("ASC", "DESC")) ? @$_REQUEST["orderDirection"] : "ASC");
         //calculate the number of rows in this table
         $rscount = mysql_query("SELECT count(*) AS cnt FROM `modelName` $where");
         $row_rscount = mysql_fetch_assoc($rscount);
         $totalrows = (int) $row_rscount["cnt"];
         //get the page number, and the page size
         $pageNum = (int)@$_REQUEST["pageNum"];
         $pageSize = (int)@$_REQUEST["pageSize"];
         //calculate the start row for the limit clause
         $start = $pageNum * $pageSize;
         //construct the query, using the where and order condition
         $query_recordset = "SELECT id,subscriber_id,lastName,firstName,birthdate,gender FROM `modelName` $where $order";
         //if we use pagination, add the limit clause
         if ($pageNum >= 0 && $pageSize > 0) {     
              $query_recordset = sprintf("%s LIMIT %d, %d", $query_recordset, $start, $pageSize);
         $recordset = mysql_query($query_recordset, $conn);
         //if we have rows in the table, loop through them and fill the array
         $toret = array();
         while ($row_recordset = mysql_fetch_assoc($recordset)) {
              array_push($toret, $row_recordset);
         //create the standard response structure
         $toret = array(
              "data" => $toret,
              "metadata" => array (
                   "totalRows" => $totalrows,
                   "pageNum" => $pageNum
         return $toret;
    * constructs and executes a sql count query against the selected database
    * can take the following parameters:
    * $_REQUEST["filter"] - the filter value
    * returns : an array of the form
    * array (
    *           data => number_of_rows,
    *           metadata => array()
    function rowCount() {
         global $conn, $filter_field, $filter_type;
         $where = "";
         if (@$_REQUEST['filter'] != "") {
              $where = "WHERE " . $filter_field . " LIKE " . GetSQLValueStringForSelect(@$_REQUEST["filter"], $filter_type);     
         //calculate the number of rows in this table
         $rscount = mysql_query("SELECT count(*) AS cnt FROM `modelName` $where");
         $row_rscount = mysql_fetch_assoc($rscount);
         $totalrows = (int) $row_rscount["cnt"];
         //create the standard response structure
         $toret = array(
              "data" => $totalrows,
              "metadata" => array()
         return $toret;

  • MySQL Locks

    Hi,
    This is quite complicated, and probably I'm making a big mess in many concepts... but can someone help me with this??
    All right... I'm using MySQL DB, and it's default table types do not support transactions, so I'm supposed to use table locks instead. There are also InnoDB table types in MySQL which support transactions, but since the server I'm putting all in is still unknown, I don't want to assume it will support InnoDB tables.
    Then, when using JDBC API to access this DB, it seems by the documentation that all results are in the ResultSet type. But this representation is in fact a pointer to the DB row, and it pulls up the data just when requested.
    For example, if I execute a select statement that returns me 10 rows, one will be read directly from the DB everytime i call the method next.
    Is everything correct until now?
    OK... the problem is... if I lock the table in order to protect this reading from other threads writings and the rows take some time to process individually, will the table be locked all that long? Or the JDBC implementation does all that for me and I don't even have to use locks? Or this is just an illusion and all the results are read and there is no further concurrency problem - after I release the lock, of course?
    I know select, update and other operations are atomic in mysql default tables, but this will be used all over...
    One last thing, I'm using MySQL Connector/J 3.0 JDBC driver.
    I hope I could describe my doubt...
    Thanks

    There are also InnoDB table types in MySQL which support
    transactions, but since the server I'm putting all in
    is still unknown, I don't want to assume it will
    support InnoDB tables.If you really need transactions, I think you can safely assume that it is available, since MySQL-Max versions since around 3.23.40+ have supported InnoDB.
    Still, if you want to use MyISAM, you could, but individual table locking won't really give you transactional semantics. It may prevent premature dirty reads, but that's all, and it's an extremely expensive way of doing this.
    But you may not need to do this, since the MyISAM table manager automatically locks the table when processing a query (so that no inserts or updates can take place while the query is being processed). So you won't get inconsistent results in terms of reading the result of half of an update, for instance.
    However, you will never really get transactional semantics unless you lock the entire DB, but that's REALLY nasty.
    But this representation is in fact a pointer to the DB
    row, and it pulls up the data just when requested.False. MySQL doesn't have anything like DB cursors, so the entire
    query result is read into memory as soon as you executeQuery(),
    and the next() simply returns you values from memory.
    So yes, if you start a query without a restrictive WHERE clause and without a LIMIT clause on a giant table, you'll run out of memory before you can even get the first row.
    OK... the problem is... if I lock the table in order
    to protect this reading from other threads writings
    and the rows take some time to process individually,
    will the table be locked all that long? No - see the above. If you're not using explicit locking, the tables being queried will be temporarily locked until the results are generated into the server's memory, and then the locks are released. Then the results are transferred completely to the client's JDBC driver memory, and it then feeds the results on each next() call.
    On the other hand, if you lock the DB, you won't get a chance to unlock the DB until all the above steps are completed (i.e. until the last byte of the result set has been sent back to the JDBC driver and processed by it into the ResultSet).
    This would make your application nearly unusable.
    Or the JDBC implementation does all that for me and I don't
    even have to use locks? Well, JDBC won't do this for you. If all you want is a clean query without partial individual-update side-effects, you can get that for free without doing any locking, courtesy of MySQL's MyISAM table manager.
    However, if you need transactional semantics (i.e. you want to consider a series of updates or inserts as one transaction, and don't want any other query to see partial results after a subset of those updates), then:
    (a) you'll have to do explicit locking, with all the hazards described above,
    OR
    (b) you'll have to break down and use InnoDB, and ask your users to install MySQL-Max 3.23.latest or 4.0.latest.

  • Beginner: Getting syntax error on WHERE clause in SELECT

    I'm very new to php and mySQL.  Am using DW master/detail to generate to basic code I need.  One thing I need to do is modify a select statement in the master to include a WHERE clause to limit the selection to a particular value in one field.
    I'm getting a syntax error with the WHERE clause I'm adding to the map select statement.
    This is the portion of the error message showing the error location:
    'WHERE Group='Community' LIMIT 0, 10'
    The php that generated the select is:
    $query_maps = "SELECT * FROM tblmaps ORDER BY tblmaps.DispSeq";
    $query_limit_maps = sprintf("%s WHERE Group='%s' LIMIT %d, %d", $query_maps, $selectGroup, $startRow_maps, $maxRows_maps);
    This approach to creating the select statement is from the code generated for the master page.  It adds the LIMIT clause.  All I did was add the "WHERE Group='%s' and the $selectGroup variable which comes from earlier code.  You can see that the $selectGroup variable is equal to the "Community: group.
    I've scanned the web to see what syntax error I might be making but haven't found anything that explains it.
    The full resolved select statement is:
    SELECT * FROM tblmaps ORDER BY tblmaps.DispSeq WHERE Group='Community' LIMIT 0,10
    What am I not seeing?
    Tom

    Thanks.  Make sense but changing that didn't help.
    Here's the error message I'm getting:
    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 'Group='Community' ORDER BY tblmaps.DispSeq LIMIT 0, 10' at line 1
    The full select (from a debugging ECHO I inserted) is:
    SELECT * FROM tblmaps WHERE Group='Community' ORDER BY tblmaps.DispSeq LIMIT 0, 10
    Note that when I take the WHERE clause out, there is no syntax error.

Maybe you are looking for