NodeJS code is given below:
app.get('/search', function(req, res){
var keyword = req.query.q;
con.query("SELECT Post_Title, Post_Icon, Post_Cont, Post_Author, Post_Date FROM Posts WHERE Post_Title LIKE '" + keyword + "' OR Post_Icon LIKE '" + keyword + "' OR Post_Cont LIKE '" + keyword + "' OR Post_Author LIKE '" + keyword + "' OR Post_Date LIKE '" + keyword + "' ORDER BY Post_Date ASC", function (err, result) {
if (err){
console.log("Error on DB SELECT.");
console.log(err);
tellSelectError(req, res);
}else{
console.log("Database selected");
console.log(result);
/*res.render('index', {
info: info,
result: result
});*/
res.json(result);
}
});
});
It send empty json to client browser.
Screenshot is uploaded at: https://i.stack.imgur.com/kpSDA.jpg
Please help.....
This code is working:
SELECT * FROM Posts WHERE Post_ID = " + keyword but I want to use LIKE with all coloums of Posts excluding Post_ID.
console.log(err); logs no error.
Got a news:
When I change the SQL to SELECT * FROM Posts, it correctly returning all raws but SELECT Post_Title, Post_Icon, Post_Cont, Post_Author, Post_Date FROM Posts WHERE Post_Title LIKE '" + keyword + "' OR Post_Icon LIKE '" + keyword + "' OR Post_Cont LIKE '" + keyword + "' OR Post_Author LIKE '" + keyword + "' OR Post_Date LIKE '" + keyword + "' ORDER BY Post_Date ASC is not working as expected.
You need to wrap the values you pass to the query in quotes. So the correct syntax for you should be:
"SELECT Post_Title, Post_Icon, Post_Cont, Post_Author, Post_Date
FROM Posts
WHERE Post_Title LIKE '" + keyword + "' OR Post_Icon LIKE '" + keyword + "' OR Post_Cont LIKE '" + keyword + "' OR Post_Author LIKE '" + keyword + "' OR Post_Date LIKE '" + keyword + "' ORDER BY Post_Date ASC"
Note: LIKE is an operator that is used instead of = to search for a value inside a field. = will try to match the full field. To do so LIKE use a wildcard (%) in three different options:
%keyword the value ends with keyword;
keyword% the value begins with keyword;
%keywords% the value contains somewhere the keyword
If you don't use the wildcard it is useless to use LIKE
Related
I can't get rid of the single quote from around null here:
const obj = {"ItemData": {
"ItemId": 4335549,
"CustID": null,
"dateCreated": "2021-02-01 07:50:51.1670000",
"amount": 10.99
}
}
let x= "'" + obj.ItemData.ItemId + "|''" + obj.ItemData.CustID + "''|" + obj.ItemData.dateCreated +
"|" + obj.ItemData.amount + "'"
regx = /'null'/ig
console.log(x.replaceAll(regx, null))
I get this:
'4335549|'null'|2021-02-01 07:50:51.1670000|10.99'
I want this:
'4335549|null|2021-02-01 07:50:51.1670000|10.99'
Also tried standard replace, same result.
How to remove the quotes from around null?
try this
regx = /''null''/ig
console.log(x.replaceAll(regx, null));
or you can try more generic
let x="";
Object.keys(obj.ItemData).forEach((key) => { x += "|" + obj.ItemData[key] });
x= "'" + x.substring(1) + "'";
You can use the following code to only insert the quotes when the value is not null
let x= "'" + obj.ItemData.ItemId + "|" +
((obj.ItemData.CustID === null) ? "null" : ("'" + obj.ItemData.CustID + "'")) + "|" + obj.ItemData.dateCreated + "|" + obj.ItemData.amount + "'"
i created several sql statements in node.js and now i want to execute them on my db. However, the query string is not executed as coded.
This is my function to generate the query string.
function insertProducts(products) {
if (!connection) {
// Create MYSQL-Connection
console.log('BUILDING connection to DB');
connection = getConnection();
connection.connect();
}
let query = "";
for (let i = 0; i < products.length; i++) {
// Iterate trough the products array and create a sql query
query += "INSERT INTO `tShortDescription`(`ShortDescription`, `Language`) VALUES ('" + products[i].short_description + "', 'DE'); " +
"INSERT INTO `tDescription`(`Description`, `Language`) VALUES ('" + products[i].description + "', 'DE'); " +
"INSERT INTO `tManufacturer`(`Name`) VALUES ('" + products[i].manufactur + "'); " +
"INSERT INTO `tSupplier`(`Name`) VALUES ('" + products[i].supplier + "'); " +
"INSERT INTO `tProduct`(`Sku`, `Title`, `ShortDescriptionId`, `DescriptionId`, `WohlesalePrice`, `SellingPrice`, `Quantity`, " +
"`ManufacturerId`, `SupplierId`, `Ean`) VALUES ('" + products[i].sku + "', '" + products[i].name + "', " +
"(SELECT id FROM tShortDescription WHERE ShortDescription = '" + products[i].short_description + "' LIMIT 1), " +
"(SELECT id FROM tDescription WHERE Description LIKE '" + products[i].description + "' LIMIT 1), " +
products[i].wholesale_price + ", " + products[i].selling_price + ", " + products[i].quantity + ", " +
"(SELECT id FROM tManufacturer WHERE Name = '" + products[i].manufactur + "' LIMIT 1), " +
"(SELECT id FROM tSupplier WHERE Name = '" + products[i].supplier + "' LIMIT 1), " + products[i].ean + "); ";
for (let j = 0; j < products[i].categories.length; j++) {
// Ad all categories to query
query += "INSERT INTO `rtCategory`(`ProductId`, `CategoryId`) " +
"VALUES ((SELECT `Id` FROM `tProduct` WHERE sku = '" + products[i].sku + "' LIMIT 1), " +
"(SELECT `Id` FROM `tCategory` WHERE Id = " + products[i].categories[j].src + " LIMIT 1)); "
for (let c = 0; c < products[i].images.length; c++) {
// Ad all images to query
query += "INSERT INTO `tImage`(`Url`) VALUES ('" + products[i].images[c].src + "'); " +
"INSERT INTO `rtImage`(`ProductId`, `ImageId`) " +
"VALUES ((SELECT `Id` FROM `tProduct` WHERE sku = '" + products[i].sku + "' LIMIT 1), " +
"(SELECT `Id` FROM `tImage` WHERE url = '" + products[i].images[c].src + "' LIMIT 1)); "
}
}
}
query = query.replace(/[\n\r\t]/g,);
if (query != "") {
// Create new Product in DB
return new Promise((resolve, reject) => {
connection.query(query, function (error, results, fields) {
if (error) { console.log(error) };
console.log('INSERTING successful');
resolve(results);
});
});
} else {
console.log('There are no new products to insert in db');
}
}
If i console.log(query) (before the query is ecexuted on my db) and execute the string directly in php myadmin, everything works fine but if i execute the query in code like connection.query(query, function (error, results, fields)....., i got several errors.
Error msg in terminal:
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: "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 'INSERT INTO `tDescription`(`Description`, `Language`) VALUES ('<p><strong>Tantra' at line 1",
sqlState: '42000',
index: 0,
I also get the sql query returned in terminal because of the error, and if i execute this query directly in php myadmin i also get an error ->
SQL query: Documentation
INSERT INTO `rtImage`(`ProductId`, `ImageId`) VALUES ((SELECT `Id` FROM `tProduct` WHERE sku = 'H1500148' LM
IT 1), (SELECT `Id` FROM `tImage` WHERE url = 'https://cdnbigbuy.com/images/H1500148_409897.jpg' LIMIT 1))
MySQL said: Documentation
#1064 - 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 'LM
IT 1), (SELECT `Id` FROM `tImage` WHERE url = 'https://cdnbigbuy.com/images' at line 1
It looks as if the LIMIT is somehow divided ...use near 'LM IT 1)....
I hope you understand where the problem is and someone might have a tip.
Your query is processed as 'LIMIT' it's just a new line in the console where the error showed up.
You should not be using string concatenation (or even template literals) for SQL queries under any circumstances because 1. It very likely the source of your problem. 2. It's very dangerous as it allows SQL injection attacks.
Use parameters instead. Here's a example:
connection.query("SELECT * FROM bank_accounts WHERE dob = ? AND bank_account = ?",[
req.body.dob,
req.body.account_number
],function(error, results){});
To read more about SQL injections and placeholders read this article.
Thanks for the helpful tips.
The problem was that I didn't set multiple statements: true in my code. This var is by default false and should be true, otherwise it is not possible to execute several queries once at a request!
I have a query, but I am not sure how to allow NodeJS to input it with variables.. how do I achieve this? What is the best way?
var sql = (
"INSERT INTO stats_tmp (
id,
timestamp,
campaign_nm,
calls,
seconds,
answered,
failure,
dnc,
amd,
transfers,
transfer_seconds,
cost
) VALUES ("
+ estarr[0].id + ", "
+ estarr[0].timestamp + ", "
+ estarr[0].name + ", "
+ estarr[1].calls + ", "
+ estarr[1].seconds + ", "
+ estarr[1].answers + ", "
+ estarr[1].failures + ", "
+ estarr[1].dncs + ", "
+ estarr[1].amd + ", "
+ estarr[1].transfers + ", "
+ estarr[1].transfers + ", "
+ estarr[1].transferseconds + ", "
+ estarr[1].cost
+ ")"
);
You want to use prepared statements.
Consider:
var query = connection.query(
'INSERT INTO stats_tmp (
id,
timestamp,
campaign_nm,
calls,
seconds,
answered,
failure,
dnc,
amd,
transfers,
transfer_seconds,
cost
) VALUES (
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
?
)',
[
estarr[0].id,
estarr[0].timestamp,
estarr[0].name,
estarr[1].calls,
estarr[1].seconds,
estarr[1].answers,
estarr[1].failures,
estarr[1].dncs,
estarr[1].amd,
estarr[1].transfers,
estarr[1].transfers,
estarr[1].transferseconds,
estarr[1].cost
],
function(err, results) {
...
});
My sql query is working fine, until I try to add the absolute last row. How can I get that part working?
INSERT INTO posts (ssp_order, ssp_id, ssp_ss_id, ssp_c_id)
SELECT COALESCE(MAX(ssp_order),0)+1 ,
" . $sspid . "," . $ssid . "," . $cid . "
FROM posts
WHERE ssp_ss_id = " . $ssid . "
ON DUPLICATE KEY UPDATE
ssp_status = 0,
ssp_order = SELECT COALESCE(MAX(ssp_order),0)+1 FROM posts
(please don't worry about the safety of the variables in there)
Reference the table used in the select statement rather than using a subquery
INSERT INTO posts (ssp_order, ssp_id, ssp_ss_id, ssp_c_id)
SELECT maxssporder ,sspid,ssid,cid from
(SELECT COALESCE(MAX(ssp_order),0)+1 as maxssporder,
" . $sspid . " as sspid," . $ssid . " as ssid," . $cid . " as cid
FROM posts p
WHERE ssp_ss_id = " . $ssid . ") q
ON DUPLICATE KEY UPDATE
ssp_status = 0,
ssp_order = q.maxssporder
I have a table
items: id, userid, item_name, item_description
I want to update a row and used the following sql statement for it.
$updateQuery = "UPDATE items SET item_name = '$item_name',
item_desc = '$item_desc' WHERE userid = '$userid'
AND item_name = '$old_name'";
But it fails. Is it because I used the item_name field, which is to be updated, for selecting the row?
I think I see the problem
item_desc = '$item_desc'
"4 columns id, userid, item_name, item_description."
Change your query to
$updateQuery = "UPDATE items SET item_name = '$item_name', item_description = '$item_desc' WHERE userid = '$userid' AND item_name = '$old_name'";
you not update item_name because you used it in where clause
or
you can echo this string and run in database terminal to verify.
Try :
$updateQuery = "UPDATE items SET item_name = '" . $item_name . "', item_desc = '" . $item_desc . "' WHERE userid = " . $userid . " AND item_name = '" . $old_name . "';"
Please notice, in your query, you are referring the last column as "item_desc" which does not exist, as the actual column name is "item_description" .
MySQL is treating "item_desc" as a separate column in your table, but unable to find it, and hence the error.
Also, it is a good idea to pay attention to how you are concatenating your variable to your query. After equal to(=) sign, always use this notation ' ".$variable_name." ' to concatenate. Example:
select column1, column2 from table1 where (column1 = ' ".$variable_name." ' && column2 = ' ".$variable_name." ') ";
You have to concatenate the strings.
$updateQuery = "UPDATE items SET item_name = '" . $item_name . "', item_desc = '" . $item_desc . "' WHERE userid = " . $userid . " AND item_name = '" . $old_name . "'";
Instead of item_desc, it should be item_description.