I'm using nodeJs and mysql package.
I want to use LIKE sql statement with varibale.
this is source code :
var likemobile = '%'+mobile;
var query = "SELECT vtiger_contactaddress.contactaddressid as 'leadid',
vtiger_contactaddress.mobile,
vtiger_contactaddress.phone
FROM `vtiger_contactaddress`
INNER JOIN `vtiger_crmentity`
ON vtiger_crmentity.crmid=vtiger_contactaddress.contactaddressid AND
vtiger_crmentity.deleted=0 AND
vtiger_contactaddress.mobile LIKE "+likemobile+" OR
vtiger_contactaddress.phone LIKE "+likemobile;
and this is error that returns:
Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual th
at corresponds to your MySQL server version for the right syntax to use near '%8
8436500 OR vtiger_leadaddress.phone LIKE %88436500' at line 1
You need to enclose the like pattern in single quotes.
Two other suggestions:
Only use single quotes for string and date constants (not column aliases).
Use parameterized queries, so you are not putting user input into query strings.
If you indeed are using node-mysql, you should run queries as instructed in the documentation. Assuming you have a connection object already, querying with bind variables becomes simple:
connection.query({
sql : "SELECT vtiger_contactaddress.contactaddressid as leadid, "
+ " vtiger_contactaddress.mobile, "
+ " vtiger_contactaddress.phone "
+ "FROM `vtiger_contactaddress` "
+ "INNER JOIN `vtiger_crmentity` "
+ " ON vtiger_crmentity.crmid=vtiger_contactaddress.contactaddressid"
+ " AND vtiger_crmentity.deleted=0 AND "
+ " (vtiger_contactaddress.mobile LIKE concat('%', ?) OR "
+ " vtiger_contactaddress.phone LIKE concat('%', ?))",
values: [mobile, mobile]
}, function (error, results, fields) {
// error will be an Error if one occurred during the query
// results will contain the results of the query
// fields will contain information about the returned results fields (if any)
});
Things to note here:
Bind variables are used, preventing SQL Injection
The concat function is used for prefixing the (sanitized) input with the wildcard character (%)
The two query conditions that are ORed together are now separated with parenthesis from vtiger_crmentity.deleted=0, which is probably what you want
You need to write the resultset-handling code in the callback function, accessing the data through the results and fields variables
#Gordon Linoff is correct. Somelike this:
var likemobile = mobile;
var query = "SELECT vtiger_contactaddress.contactaddressid as 'leadid', vtiger_contactaddress.mobile, vtiger_contactaddress.phone FROM `vtiger_contactaddress` INNER JOIN `vtiger_crmentity` ON vtiger_crmentity.crmid=vtiger_contactaddress.contactaddressid AND vtiger_crmentity.deleted=0 AND vtiger_contactaddress.mobile LIKE '%"+likemobile+"%' OR vtiger_contactaddress.phone LIKE '%"+likemobile+"%'";
... AND vtiger_contactaddress.mobile LIKE '%" + likemobile + "%' OR vtiger_contactaddress.phone LIKE %" + likemobile + "%";
try this..
var likemobile = mobile;
var query = "SELECT vtiger_contactaddress.contactaddressid as 'leadid',
vtiger_contactaddress.mobile,
vtiger_contactaddress.phone
FROM `vtiger_contactaddress`
INNER JOIN `vtiger_crmentity`
ON vtiger_crmentity.crmid=vtiger_contactaddress.contactaddressid AND
vtiger_crmentity.deleted=0 AND
vtiger_contactaddress.mobile LIKE '% "+likemobile+"%' OR
vtiger_contactaddress.phone LIKE '%"+likemobile +"%'";
Related
Why can you not use parameters in an SQL statement as the column name? I found that out after two hours of thinking what the problem could be. The only way it seemed possible was by doing it in a way it could be vulnerable to SQL injections (which for me wasn't a problem because the parameters are generated serverside).
This works:
string cmdgetValues = "SELECT " + column + " FROM user WHERE " + filterColumn + " = #filter";
MySqlCommand getValues = new MySqlCommand(cmdgetValues, connectionDB);
getValues.Parameters.AddWithValue("#filter", filterValue);
This doesn't work:
string cmdgetValues = "SELECT #column FROM user WHERE #filterColumn = #filter";
MySqlCommand getValues = new MySqlCommand(cmdgetValues, connectionDB);
getValues.Parameters.AddWithValue("#column", column);
getValues.Parameters.AddWithValue("#filterColumn", filterColumn);
getValues.Parameters.AddWithValue("#filter", filterValue);
Why is this? And is it intended?
Because select columns are fundamental query
You can't parameterise the fundamental query, so you have to build the query at the code.
If you want to decide the query columns runtime maybe you can try to use Prepared SQL Statement Syntax in Mysql.
i have this code here:
var sql = "select shr_id, shc_id " +
"from tbox_operational.shipment_ref " +
"inner join tbox_operational.shipment_collo_ref using (shr_id) " +
"where shr_insdtm between ?dateTimeFrom";
var parameters = new List<MySqlParameter> {
new MySqlParameter("?dateTimeFrom", dateTimeFrom.ToString("yyyy/MM/dd HH:mm:ss"))
};
var query = (from db in context.Database.SqlQuery<ShridsModel>(sql, parameters)
select db).ToList();
return query;
But it keeps me getting this error:
{"Parameter '?dateTimeFrom' must be defined."}
i have also in my connection string:
server=xxx;user id=runtime;password=xxxx;AllowUserVariables=True;
What am i doing wrong here?
I have solved...
Instead of passing a list of the parameters, i pass each one individual and he recognizes it all
I have an issue with an sql statement and i dont know how to handle it. Here is the problem:
query = "INSERT INTO `mmr`(`userID`, `RunningProjects`, `MainOrders`) VALUES ("
+ session.getAttribute("id")
+ ",'"
+ request.getParameter("RunningProjects")
+ "','"
+ request.getParameter("MainOrders")')";
The values are obtained from the post form which contains free text. The problem is, whenever a user enters characters like ', i will get an error because that tells the compiler that the value is over here(i suppose) and now look for the next value. I don't know how to include these characters and send them to database without having an error. Any help would be appreciated. Thank you.
The character ' is used to surround literals in MySQL. And if any data contains such character as part of it, we have to escape it. This can be done using Prepared Statement in Java.
Change your query code accordingly.
query = "INSERT INTO `mmr`(`userID`, `RunningProjects`, `MainOrders`)
VALUES ( ?, ?,? )";
Now define a PreparedStatement instance and use it to bind values.
PreparedStatement pst = con.prepareStatement( query );
pst.setString( 1, session.getAttribute("id") );
pst.setString( 2, request.getParameter("RunningProjects") );
pst.setString( 3, request.getParameter("MainOrders") );
int result = pst.executeUpdate();
And, I suggest use of beans to handle business logic.
change
query = "INSERT INTO `mmr`(`userID`, `RunningProjects`, `MainOrders`) VALUES ("
+ session.getAttribute("id")
+ ",'"
+ request.getParameter("RunningProjects")
+ "','"
+ request.getParameter("MainOrders")
+ "')";
I think you are using normal statement in your JDBC code. Instead, I would suggest you to use Prepared statement. Prepared statement is generally used to eliminate this kind of problem and caching issue. If you will use prepared statement I think your problem will be solved
String name = request. getParameter ("name");
String queryString ="SELECT * FROM empy WHERE name LIKE '%'"+sname+"''";
I am using this query to search textfiled entering values. But it displays an error message..
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'textfiled value''' at line 1
You are trying to use the invalid variable 'sname' whereas you have declared the variable as 'name'
Try this
String queryString :
"SELECT * FROM empy WHERE name LIKE '%"+name+"'";
Also, if you can see the logs, see that the query generated is correct or not by hitting it directly on MySQL.
Remove the extra ' from your query. It should be like this:
SELECT * FROM empy WHERE name LIKE '%MySname'
Try this: "SELECT * FROM empy WHERE name LIKE '%" + sname + "'"
The variable name is name not sname. Also remove the ''
String queryString ="SELECT * FROM empy WHERE name LIKE '%"+name+"'";
Try this
String queryString ="SELECT * FROM empy WHERE name LIKE '%" + name + "';
I'm using the extra() modifier in a view.
(See http://docs.djangoproject.com/en/1.1/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none )
Here's the the code:
def viewname(request)
...
exact_matchstrings=[]
exact_matchstrings.append("(accountprofile.first_name LIKE '" + term + "')")
exact_matchstrings.append("(accountprofile.first_name LIKE '" + term + '\%' + "')")
extraquerystring = " + ".join(exact_matchstrings)
return_queryset = return_queryset.extra(
select = { 'match_weight': extraquerystring },
)
The two append statements above are almost completely alike except that the second adds a % SQL wildcard character. This is causing an error; the statement without the % causes no problems. What's going on with the %? I'm surprised that django thinks this character is not defined, since it's in SQL specification. For example, the following SQL statement executes just fine:
select (first_name like "Car") + (first_name like "Car%") from accountprofile;
But trying to run it via the extra() modifier in my view code and evaluating the resulting queryset gives me an error. I think "%" needs to be escaped, so I tried that already. Any ideas?
Just ran into this issue ourselves doing a extra query with LIKE. To escape a % you need to do %%
Percentage sign not working
It looks like you are missing some quotes from the 2nd string. And I'm not sure that you need to escape the percent (%) unless this is required by django.
_matchstrings.append("(accountprofile.first_name LIKE '" + term + "%" + "')")