Mysql select statement where = works and LIKE fails
I am using Flash Builder 4. On the server side I use php and mysql. I created a php dataservice using FB4. My plan had been to allow users to enter a search term and query the database using a "LIKE" statement. FB4 created the php code that I simply modified changing the parameter name. The input parameter is a string.
public function getT_caseByID($searchTerm) {
$stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename WHERE (title = ?)");
$this->throwExceptionOnError();
mysqli_stmt_bind_param($stmt, 'i', $searchTerm);
$this->throwExceptionOnError();
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
mysqli_stmt_bind_result($stmt, $row->idt_case, $row->title, $row->id_author, $row->comments);
if(mysqli_stmt_fetch($stmt)) {
return $row;
} else {
return null;
A look at FB4 shows this code returns data.
This code works fine but if I make the below change it fails, even when I use the wildcard %. the only change is "=" to "LIKE".
public function getT_caseByID($searchTerm) {
$stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename WHERE (title LIKE ?)");
$this->throwExceptionOnError();
mysqli_stmt_bind_param($stmt, 'i', $searchTerm);
$this->throwExceptionOnError();
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
mysqli_stmt_bind_result($stmt, $row->idt_case, $row->title, $row->id_author, $row->comments);
if(mysqli_stmt_fetch($stmt)) {
return $row;
} else {
return null;
A look into FB4 shows "void".
Any help would be appreciated. I am using localhost on Apache Server on a development computer with Windows XP.
correctio0n on the select statement
select statement code*********
select
apspnr astspr aobjnr apspid
bpsphi bposid
caufnr cpspel
dinact dstat
eudate eusnam eutime "estat
F~TXT04
g~estat
G~TXT04
into corresponding fields of table itobj
from proj as a
inner join prps as b on apspnr = bpsphi
inner join aufk as c on bpspnr = cpspel
inner join jest as d on cobjnr = dobjnr
inner join jcds as e on dobjnr = eobjnr
and dstat = estat
inner join tj02t as f on estat = fistat
inner join tj30t as g on astspr = gstsma
for all entries in itparm
where apspid = itparm-pspid "or estat = itparm-psy )
or bposid = itparm-posid "or estat = itparm-wsy )
or caufnr = itparm-aufnr "or estat = itparm-nsy )
and ( dinact 'X' or einact 'X')
and fspras = 'E' and gspras = 'E'.
Similar Messages
-
Concat java variable to a MySql select statement and exeucte
Hi,
I am trying to append a variable to a MySql select statement.
Overview: I need to retrieve data from a MySql database with a java variable as a reference and select the data in the database based on that variable.
CODE THAT I CURRENTLY HAVE:
// Declare variables
Connection conn = null;
Statement st = null;
Resultset rs2 = null;
String st2 = null;
String keyid = null;
// Connect to database
try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://" + mysql_host + ":3306/" + mysql_database, mysql_login, mysql_password);
st = conn.createStatement();
// Select data in Database with hanging equal sign
st2 = ("SELECT * FROM table WHERE keyid= ");
// Append keyid to hanging equal sign of select statement
rs2 = st.executeQuery(st2 + keyid);
}This is not working when I try to display the data.What is not working about it? Is there an error message? Stack Trace?
Where do you get the value of keyId from?
I would suggest that you use a prepared statement rather than building up a sql string like this. It prevents sql injection attacks
// Declare variables
Connection conn = null;
PreparedStatement stmt = null;
Resultset rs2 = null;
String sql= null;
String keyid = null;
// Connect to database
try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://" + mysql_host + ":3306/" + mysql_database, mysql_login, mysql_password);
// Select data in Database with place holder for parameter
sql = "SELECT * FROM table WHERE keyid= ?";
// prepare the statement
stmt = conn.prepareStatement(sql);
// set the value of key id to use with the query
stmt.setString(1, keyId);
// run the query
rs2 = st.executeQuery();
catch (Exception e){
System.out.println("An error occurred " + e.getMessage());
e.printStackTrace();
finally{
if (rs2 != null) try { rs2.close(); } catch(SQLException ex){}
if (stmt != null) try { stmt.close(); } catch(SQLException ex){}
if (conn != null) try { con.close(); } catch(SQLException ex){}
} -
Conditional Mysql select statement
HI Folks
can anyone point me in the right direction with a MySQL statement.
I will try to layout my thinking here:
I have a form with three inputs area, name and search. I am trying to write a Mysql select statement that selects records from a single table if they match the criteria. Easy for two variables but I'm lost after that.
1. The form includes these three inputs:
area - drop down menu (Any as default)
name - drop down menu (Any as default)
search box - text area (Blank as default)
2. The form submits to itself leaving me with these three variables
$search=$_GET['search']
$area=$_GET['area']
$name=$_GET['area']
SELECT * FROM database WHERE database.description LIKE '%$search%' AND database.area LIKE '$area' AND database.name LIKE '$name'
3. This is where I get confused. How do I get the SQL to Select everything correctly. I have tried using PHP if/else code to fix it but I end up running around in circles with six different Select statements and haven't yet got that to work.
So I have come to the conclusion that there must be an easier way. I see search forms with dozens of search criteria on websites every day an d I only have 3 - so it can't be this complicated. Right?
I know I need to start from the beginning again but can anyone let me know how to approach it before I begin?
Cheers
DaveTypically, I would build the where clause dynamically, based upon the values in your form. If the form field contains 'Any', leave it out of the where clause. So you can test each field value and either append or not to the end of the where clause.
-
hi to all,
I am trying to write use inner joining . here is code
DATA:tabname LIKE dd02L-tabname,
table_disc LIKE dd02t-ddtext.
SELECT dd02ltabname dd02tddtext INTO (tabname,table_disc)
FROM dd02l INNER JOIN dd02t on dd02ltabname = dd02ttabname
WHERE dd02tddlanguage = 'E' AND dd02ltabclass = 'TRANSP'
AND dd02L~tabname = 'ZANKI*'.
endselect.
write : tabname.
I also checked in tables dd02t and dd02l for the table zanki* and data available in both table . but here select statement not working .do u have any idea about this. thank youHi,
I executed the ur inner join conditin by commenting 'z*' it's working fine.
I think where condition is not getting satisfied so u r not getting any data.
Please conform in where condition you need * 'AND'* or OR
I change decalration as below.
DATA:tabname type TABNAME,
table_disc type AS4TEXT.
SELECT dd02l~tabname
dd02t~ddtext INTO (tabname, table_disc)
FROM dd02l INNER JOIN dd02t on dd02l~tabname = dd02t~tabname
WHERE dd02t~ddlanguage = 'E' AND
dd02l~tabclass = 'TRANSP'AND
dd02L~tabname = 'ZANKI*'.
endselect.
write : tabname.
Regards,
Pravin -
MySQL Select Statement Help Required
I am trying to generate a report in VS 2008 (C#) using a mysql select statement but cannot get it right.
I have groups that meet on a weekly basis on different days. I want to generate a report that shows me all the members that have not attended their group where they have missed 3 meetings in a row.
Below is the select statement I have tried but it does not give me the results I am looking for. I have tried to look at all the meetings in a 4 week period but would prefer to look at the last 3 meetings that are recorded. Some groups might not record a meeting every week. So I want to look at the last 3 recorded meetings and count each members attendance and only report on the members with more than 3 meetings missed.
SELECT COUNT(`groupattendance`.`Attended`) AS Attendance, `smallgroupform`.`MeetingDate`, `userinfo`.`FirstName`, `userinfo`.`Surname`, `smallgroup`.`GroupName`, `groupattendance`.`Attended`, `groupattendance`.`UserID`, `groupattendance`.`GroupID`
FROM ((`anatomy`.`groupattendance` `groupattendance`
INNER JOIN `anatomy`.`smallgroupform` `smallgroupform` ON `groupattendance`.`FormID` = `smallgroupform`.`FormID`)
INNER JOIN `anatomy`.`userinfo` `userinfo` ON `groupattendance`.`UserID` = `userinfo`.`UserID`)
INNER JOIN `anatomy`.`smallgroup` `smallgroup` ON `groupattendance`.`GroupID` = `smallgroup`.`GroupID`
WHERE (`smallgroupform`.`MeetingDate` >= DATE_SUB(CURDATE(),INTERVAL 4 WEEK) AND `smallgroupform`.`MeetingDate` <= CURDATE()) AND `groupattendance`.`Attended` = 'False'
GROUP BY `userinfo`.`UserID`
HAVING Attendance >= 3
Thanks,
Garth.Hi Garth,
Seems no one can help you directly. Try googling your SQL request. Someone may be able to help you. At this point its not really a Cr problem.
One option is to get all the data and add filtering using the record selection formula.
Thank you
Don -
Tuning Select Statement . field sequence and where clause
Hi All
Are there any general guidelines how to write select < field sequence >where clause < field sequence ? Is that shuld be in order of the field sequence in tables?
And how to use this when we have a view or a inner - join . Is that separate from normal select statement that is using FOR ALL ENTRIES.
Please let me know any general guidelines available on this,
AmolHello Amol,
I have another hint:
The statement FOR ALL ENTRIES will package the select statements for every five entries in the internal table. So in comparison to the following code sequence...
LOOP AT itab.
SELECT * FROM table WHERE key = itab-key.
ENDLOOP
the number of select statements is reduced to 20% with
SELECT * FROM table INTO TABLE ...
FOR ALL ENTRIES IN itab
WHERE key = itab-key
If I'm expecting a <i>huge</i> amount of data a go a step further and create my own packages by building a range table with around 100-500 entries and execute a select there...
LOOP AT itab.
IF counter < 500.
APPEND itab-key TO range-tab. " just code example
ENDIF.
IF count >= 500.
SELECT * FROM table APPENDING TABLE ...
WHERE key IN range_tab
ENDIF.
" adjust and calculate counter
ENDLOOP.
* Don't forget last select statement after loop
Best wishes,
Florin -
Hi All,
I have java application which suppose to connect to MySql server and print the selected data.
The application has 4 combo boxes (first item is empty): Name, Customer, Supplier, Status.
User could choose any of these options. So there are huge number of select combinations.
Is it possible to create one select statement template something like this:
PreparedStatement stmt = con.prepareStatement( "SELECT * from database WHERE user_id = ?,
and customer_id = ?,
and supplier_id = ?,
and status = ? " );
if ( ! ComboBox.getSelectedItem().toString().isEmpty() )
stmt00.setString( 1, ComboBox.getSelectedItem().toString() );
else
stmt00.setString( 1, "*" );
etc
I'm stuck at this part stmt00.setString( 1, "*" ). Is there any way to write statement SELECT * from table WHERE column = * ?
What is the proper way to write such selection ?
Thanks in advance,
VladimirIs there any way to write statement SELECT * from table WHERE column = * ?No, that's invalid SQL.
What is the proper way to write such selection ?If you need in one case to select a single user, but in another case to select all of them, then you need to handle two different SQL statements.
1. SELECT * from table WHERE column = value
2. SELECT * from table
This has nothing to do with Java. -
Select statement - Where Condition not possible
Hi,
I am trying to extract data from sap standard table CFX_COL.I want extract based on a field which is of type string.I can see that in the table but when I code below I am getting error.Any other alterantives?
REPORT x.
TABLES:proj.
DATA: it_proj TYPE STANDARD TABLE OF proj.
DATA:wa_proj TYPE proj.
DATA: it_cfol TYPE STANDARD TABLE OF CFX_COL.
DATA:wa_cfol TYPE CFX_COL.
data:v_name type STRING.
PARAMETERS: p_pspid LIKE proj-pspid.
SELECT * FROM proj INTO CORRESPONDING FIELDS OF TABLE it_proj
WHERE pspid = p_pspid.
READ TABLE it_proj INTO wa_proj INDEX 1.
concatenate wa_proj-pspid '-' wa_proj-post1 into v_name.
select * from CFX_COL into CORRESPONDING FIELDS OF TABLE it_cfol
where name in v_name.
Error:The Field "NAME" is a long string , so it cannot be used in WHERE, ON or HAVING conditions.
Rgds
VaraHi Vara.
Select will not work if you are trying to search based on the name field as in the table CFX_COL it has data type String which basically is not content but a reference to a storage area and internally it is stored in a different format not searchable. Even , if you try to find the number of entries in the table you can not put any value in this field as it will not be available for input as it doesn't contain any value.
STRING: Character string with variable length This data type can only be used in types (data elements, structures, table types) and domains. In the Dictionary a length can be specified for this type (at least 256 characters). It may be used in database tables, however, only with restrictions. For a description of them refer to the documentation of the ABAP statement 'STRING' . In ABAP, this type is implemented as a reference to a storage area of variable size. As default for the output length 132 characters are proposed. You cannot attach search helps to components of this type.
http://help.sap.com/saphelp_40b/helpdata/en/cf/21f2e5446011d189700000e8322d00/content.htm
Regards
Apoorva -
Hi,
we are running a query with a big dunamic select statement from VB code using ADO command object. When Execute method is called system hangs and control won't return back to the application. it seems to be that there is some type limitation on Query string length. Please tell us if there is any?
we are running Oracle 8.1.7 Server on Windows 200 Server and connecting from a W2K professional, ADO 2.6 and Oracle OLEDB 8.1.7.1 OLEDB Driver.
Sample code:
Dim rs As ADODB.Recordset
Dim cmd As ADODB.Command
Set cmd = New Command
With cmd
.CommandText = ' some text with more than 2500 characters
.CommandType = adCmdText
Set rs = .Execute
End With
when i debug using VB6 and when .Execute line is called system hangs or return a message method <<somemethod> of <<some class name>> failed error.
Any help is appreciated.
Thanks,
AnilA stored procedure would only slow you down here if it was poorly written. I suspect you want to use the translate function. I'm cutting & pasting examples from the documentation-- a search at tahiti.oracle.com will give you all the info you'll need.
Examples
The following statement translates a license number. All letters 'ABC...Z' are translated to 'X' and all digits '012 . . . 9' are translated to '9':
SELECT TRANSLATE('2KRW229',
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'9999999999XXXXXXXXXXXXXXXXXXXXXXXXXX') "License"
FROM DUAL;
License
9XXX999
The following statement returns a license number with the characters removed and the digits remaining:
SELECT TRANSLATE('2KRW229',
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', '0123456789')
"Translate example"
FROM DUAL;
Translate example
2229
Also, LIKE '%<string>%' is going to be rather expensive simply because it has to compare the entire string and because it forces full table scans, rather than using indexes. You could speed this sort of query up by using interMedia Text (Oracle Text now in 9i). If you can eliminate one of the '%' options, you could also improve things.
My guess is that your stored procedure is inefficient and that's causing the problem-- 5k rows per table should be pretty trivial.
If you post your query over on the PL/SQL forum, there are better performance tuners than I that might have more hints for you. To get really good advice, though, you'lllikely have to get at least the execution plan for this statement and may need to do some profiling to identify the problem areas.
Justin -
MySql select statement in jsp page
Ok,
I need help with this select statement.
<%
// Determine what option is set to.
if(option == null || "".equals(option) || "Verify1".equals(option)){
if("Verify1".equals(option)){
// Retrive query specific to submitted form.
try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://" + mysql_host + ":3306/" + mysql_database, mysql_login, mysql_password);
st = conn.createStatement();
rs= st.executeQuery("SELECT organization FROM tblevent_approval WHERE MAX (keyid))";
// Get query results.
while(rs.next()){
organization = rs.getString("organization");
finally {
if(rs != null){
rs.close();
if(st != null){
st.close()
if(conn != null){
conn.close();
%>THE ERROR I AM GETTING
Syntax error, insert ")" to complete ExpressionThis line has the closing bracket inside the closing quote for the statement...
> rs= st.executeQuery("SELECT organization FROM tblevent_approval WHERE MAX (keyid))";It should be:
rs= st.executeQuery("SELECT organization FROM tblevent_approval WHERE MAX (keyid)");A simple typo ;-)
Hope this helps... -
Select Statement -- Where Clause Execution Order
What is the order of execution of the "AND" and "OR" in the WHERE clause of a Select statement?
Are the "AND"'s executed from the top down, left to right? Is it the same for the "OR"'s execution?
Thanks for any help...Not clear why you care. There is an order in which the optimizer parses the SQL (which may change from ver to ver), but this is a fairly quick operation. The order in which tables are visited and predicates evaluated is dependent on what the op[timizer does with the SQL.
Ken -
SELECT statement for efficiency and readability....
Hi ppl,
I need a output exactly similer to this select statement,
SELECT A.a,
B.a,
(CASE C.a
WHEN 'NO1' THEN D.a
ELSE NULL
END)
FROM A,B,C,D;
Is this the best way to get this output.... (efficiency and readability)
Thx..After further review, neither of our queries is the equivalent of his though. It appears we both overlooked the case where c.a='No1' AND no row in D. His query will omit that case but ours both includes it. And it also appears that your query is a far improved equivalent to mine. I added a.x to each query and corrected some syntax errors we all had...
DROP TABLE a;
CREATE TABLE A
x NUMBER,
a VARCHAR2(4)
DROP TABLE b;
CREATE TABLE B
x NUMBER,
a VARCHAR2(4)
DROP TABLE c;
CREATE TABLE C
x NUMBER,
a VARCHAR2(4)
DROP TABLE d;
CREATE TABLE D
x NUMBER,
a VARCHAR2(4)
INSERT INTO A VALUES (1,'Cola');
INSERT INTO B VALUES (1,'Colb');
INSERT INTO C VALUES (1,'No1');
INSERT INTO D VALUES (1,'Cold');
INSERT INTO A VALUES (2,'Cola');
INSERT INTO B VALUES (2,'Colb');
INSERT INTO C VALUES (2,'No1');
INSERT INTO A VALUES (3,'Cola');
INSERT INTO B VALUES (3,'Colb');
INSERT INTO C VALUES (3,'XXX');
INSERT INTO D VALUES (3,'Cold');
INSERT INTO A VALUES (4,'Cola');
INSERT INTO B VALUES (4,'Colb');
INSERT INTO C VALUES (4,'XXX');SELECT a.x,A.a, B.a, C.a, NULL
FROM A,B,C
WHERE A.x = B.x
AND B.x = C.x
AND C.a <> 'No1'
UNION
SELECT a.x,A.a, B.a, C.a, D.a
FROM A,B,C,D
WHERE A.x = B.x
AND B.x = C.x
AND C.x = D.x
AND C.a = 'No1';
X A A A NULL
1 Cola Colb No1 Cold
3 Cola Colb XXX
4 Cola Colb XXX
WITH temp AS
SELECT a.x,
a.a aa,
b.a ba,
c.a ca,
d.a da
FROM a,
b,
c,
d
WHERE a.x = b.x
AND b.x = c.x
AND c.x = d.x(+)
SELECT t1.x,
t1.aa,
t1.ba,
t1.ca,
NULL da
FROM temp t1
WHERE t1.ca != 'No1'
UNION
SELECT t2.x,
t2.aa,
t2.ba,
t2.ca,
t2.da
FROM temp t2
WHERE t2.ca = 'No1';
X AA BA CA DA
1 Cola Colb No1 Cold
2 Cola Colb No1
3 Cola Colb XXX
4 Cola Colb XXX
SELECT a.x, A.a, B.a, C.a, decode(c.a,'No1',D.a, null)
FROM A,B,C,D
WHERE A.x = B.x
AND B.x = C.x
AND C.x = D.x (+);
X A A A DECO
1 Cola Colb No1 Cold
3 Cola Colb XXX
4 Cola Colb XXX
2 Cola Colb No1
Greg -
Select query not working with like & and operator
Hi,
The below is the select query which is used to select only the failed rollup jobs from DB table ( background jobs ) the status 'A' which means only the failed roll up jobs.
select jobname status from v_op into table zjob_rollup where jobname like '%ROLLUP%'
or jobname like 'BI_AGGR%'
and status like 'A'.
Right now my internal tables is picking the job name other than status A also.
Can you please help.
Note: Ps consider the performance of select query also.
Thanks,
SivaHi,
select jobname status
from v_op
into table zjob_rollup
where ( jobname like '%ROLLUP%' or jobname like 'BI_AGGR%' )
and status = 'A'. -
How Can I Get Group By Select Statement To WorK?
How can I get Code2 to work correctly? Code1 works fine. A user enters the customer and a date range on a form and submits request. I get error message in Dreamweaver. You tried to execute a query where the specified expression field3 is not part of an aggragate function I set the Form variables to: Name Default Value RunTime Value Search_Criteria 1 Request.Form("Search") Date1 1 Request.Form("Date1") Date2 1 Request.Form("Date2") Code1. This works fine SELECT Field3, Field10, SUM(Field16) as SumofField16 FROM CustomerHistory_CP WHERE Field3 LIKE '%Search_Criteria%' AND Field6 >= #1/2/09# AND Field6 <= #1/30/09# GROUP BY Field3, Field10 Code2. I get error message SELECT Field3, Field10, SUM(Field16) as SumofField16 FROM CustomerHistory_CP WHERE Field3 LIKE '%Search_Criteria%' AND Field6 >= #Date1# AND Field6 <= #Date2# GROUP BY Field3, Field10
That requires you to enter the configuration correctly. You can find out the configuration for your email from your ISPs website in most cases. Or if you're using Gmail, Yahoo, or Hotmail you need only Google something like:
"Gmail configuration for Apple Mail" or "Hotmail configuration for Apple Mail" (without the quotes).
That should get you started..
Jeff -
I have 2 tables
Table Parent_child_table:
ID | Parent_id | Name
1 | NULL | Kitchen
2 | 1 | Freezer
3 | NULL | Garden
4 | 3 | Grass
Table Products:
ID | parent_child_table_ID | Price | Comment
1 | 2 | 111 | aaaa
2 | 4 | 12 | vv
I want to select Name from parent table where selected child ID are in PRODUCT table.....
The result would like:
|NAME|
|Kitchen
|Garden
Can someone help with this SQL SELECT ?Raivis wrote:
I have 2 tables
Table Parent_child_table:
ID | Parent_id | Name
1 | NULL | Kitchen
2 | 1 | Freezer
3 | NULL | Garden
4 | 3 | Grass
Table Products:
ID | parent_child_table_ID | Price | Comment
1 | 2 | 111 | aaaa
2 | 4 | 12 | vv
I want to select Name from parent table where selected child ID are in PRODUCT table.....
The result would like:
|NAME|
|Kitchen
|Garden
Can someone help with this SQL SELECT ?A guess
select
p.name
from Parent_child_table p
where p.parent_id is null
and exists
select
null
from Parent_child_table p1, products p2
where p1.id = p2. parent_child_table_id
and p1.parent_id = p.id
)The reason it's a guess is because you've really done nothing to outline WHY you should get the results you say you would like. The more time you spend creating a clear question, the less time you'll have to spend weeding through useless answers.
Cheers,
Maybe you are looking for
-
When ever i try to open iTunes, windows immediatly comes up with iTunes has encountered a problem and needs to close with options of debug, send error report, or dont send. What do i do to get iTunes working again?
-
Windows 7 & 8.1 Dual Boot Problem
In my pc dual booting system is generated. Both os windows 7 & 8.1 are separatly partitioned. I have used it several day,but during 2 days windows 7 has been disrupting. For that,i have only formated & reinstalled windows 7. But now i can see that wi
-
I have an Iphone 3gs and cannot send text messages to my wife. She is the only person that I cannot send or receive text messages from. Does anyone know how to correct this?
-
There is an industry standard pdf form with an underlying XML schema which can be opened in Adobe reader. The form has a custom button on Page 2 called "export" which can be manually clicked to export the XML file. We will have hundreds of these for
-
Embedding image in export to HTML
We are using SAP Crystal .NET runtime v13.0.9. We export to HTML 4.0 and embed the report output within the body of an email (not as an attachment). The report contains a link to a static image using an http URL using the Formula Editor. When receive