How to remove quotes from json null when concatenating into a string? - json

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 + "'"

Related

Not able to insert Data into the database in MFC application with MS access db

The code I have written for inserting data in the DB is: Now, after entering details from the frontend, I am clicking on the Register button, but No action is happening ?? the table for this is having the following columns:
lastName
firstName
DateOfBirth
Sex
Status
MRN
Encounter_Type
Person_ID
All of these are short text types.
Database instance is correct as it is working for other modules.
void CPatientRegistrationDlg::OnBnClickedRegister()
{
// TODO: Add your control notification handler code here
CSingLeton* st;
st = CSingLeton::getInstance();
UpdateData(TRUE);
CTime tDate = CTime::GetCurrentTime();
m_DateOfBirthCtrl.GetTime(tDate);
CString sDate = tDate.Format("%Y-%m-%d");
time_t Time = time(0);
struct tm* ti = localtime(&Time);
int nCuuretnDay = ti->tm_mday;
int nCurrentMonth = 1 + ti->tm_mon;
int nCurrentYear = 1900 + ti->tm_year;
if (m_FirstNameCtrl.GetWindowTextLength() == 0 || m_LastNameCtrl.GetWindowTextLength() == 0 || m_GenderCtrl.GetCurSel() < 0 || m_EncounterCtrl.GetCurSel() < 0 || m_StatusCtrl.GetCurSel() < 0)
{
m_sMessage.LoadString(IDS_WARNINGMESSAGE);
m_sCaption.LoadString(IDS_WARNINGCAPTION);
::MessageBox(this->GetSafeHwnd(), m_sMessage, m_sCaption, MB_ICONWARNING);
}
else
{
if (OnValidatePatientFirstName() && OnValidatePatientLastName())
{
CString sGender;
m_GenderCtrl.GetWindowText(sGender);
CString sEncounterType;
m_EncounterCtrl.GetWindowText(sEncounterType);
CString sStatus;
m_StatusCtrl.GetWindowText(sStatus);
CString sLastName;
m_LastNameCtrl.GetWindowText(sLastName);
CString sFirstName;
m_FirstNameCtrl.GetWindowText(sFirstName);
CString sMrn = OnGetPatientMrn();
if (!sMrn.IsEmpty())
{
try
{
std::string sSqlString = "INSERT INTO Person_table VALUES ('" + ConvertCStringToString(sLastName) + "', '" + ConvertCStringToString(sFirstName) + "', '" + ConvertCStringToString(sDate) + "','" + ConvertCStringToString(sGender) + "', '" + ConvertCStringToString(sStatus) + "','" + ConvertCStringToString(sMrn) + "','" + ConvertCStringToString(sEncounterType) + "')";
st->ExecuteSQL(ConvertStringToCString(sSqlString));
m_sMessage.LoadString(IDS_PATIENTMRN);
m_sCaption.LoadString(IDS_MRNNOTE);
::MessageBox(this->GetSafeHwnd(), m_sMessage + _T(" ") + sMrn, m_sCaption, MB_OK);
m_FirstNameCtrl.SetWindowText(_T(""));
m_LastNameCtrl.SetWindowText(_T(""));
m_StatusCtrl.SetCurSel(-1);
m_EncounterCtrl.SetCurSel(-1);
m_GenderCtrl.SetCurSel(-1);
ResetDate(nCurrentYear, nCurrentMonth, nCuuretnDay);
}
catch (CDBException* e)
{
OutputDebugString(e->m_strError);
}
}
}
}
}

Node js - Mysql query is not executed as coded

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!

How to insert query in NodeJS with variables

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) {
...
});

Why do I not get a response from JSON post request unless the number of rows is limited?

I am using a JSON post request to return rows from a mySQL database. My server-side language is php and unless I limit the results in sql to about 45 I don't get a response. No errors just no response. Any advice would be appreciated.
The serverside code is as follows;
<?php
include('../config.php');
$status = $_POST['status'];
$itemGrp = $_POST['itemGrp'];
$jobs_sql = "SELECT custName
,SODocNum
,itemName
,cast(thickness as decimal (4,2)) as 'thickness'
,case when ca_Description like 'Diary%' then ca_Description else 'Bespoke Diary' end as ca_Description
,Quantity
,version_id
,case when T0.rqdByDate is null then '' else T0.rqdByDate end as rqdByDate
,T0.despatchDate
,case when T0.versionStatus = 010 then '' else 'w3-disabled' end as 'disableCmpltBtn'
,case when T0.versionStatus = 010 then 'update_status_complete' else '' end as 'noclickCmpltBtn'
,case when T0.versionStatus = 009 then '' else 'w3-disabled' end as 'disableChkBtn'
,case when T0.versionStatus = 009 then 'update_status' else '' end as 'noclickChkBtn'
FROM Versions T0 left outer join components_all T1 on T0.itemCode = T1.ca_versionCFG and T1.ca_itemGroup in (117,118)
WHERE versionStatus in ('$status')
and ItmsGrpCod in ('$itemGrp')
order by thickness, T1.ca_itemCode asc, T0.despatchDate asc, SoDocNum
LIMIT 45";
$jobs_result = mysqli_query($db,$jobs_sql);
$all_array = mysqli_fetch_all($jobs_result);
echo json_encode($all_array);
?>
And this is what I have on the client side;
function get_jobs_to_bind(){
console.log("Request data from server");
$.post("/_api/jobs_to_bind_api.php",
{
status:'007',
itemGrp:'121\',\'104\',\'106'
},
function(data) //on recieve of reply
{
console.log("Build table with data")
$('#jobs_to_bind_table_body').empty();
$.each(data, function (index, item) {
var eachrow = "<tr>"
+ "<td>" + item[0] + "</td>"
+ "<td style='text-align:center'>" + item[1] + "</td>"
+ "<td>" + item[2] + "</td>"
+ "<td>" + item[3] + "</td>"
+ "<td>" + item[4] + "</td>"
+ "<td>" + item[7] + "</td>"
+ "<td>" + item[8] + "</td>"
+ "<td>" + item[5] + "</td>"
+ "<td><button class='w3-btn w3-round w3-green w3-tiny' value = '" + item[6] + "' onclick='update_status(\"008\","+ item[6] +")'>Gathered</button></td>"
+ "<td><button id='viewgathererinfo' class='w3-btn w3-round w3-green w3-tiny' value = '" + item[6] + "' onclick='getgathererinfo("+ item[6] +")'>View</button></td>"
+ "</tr>";
$('#jobs_to_bind_table_body').append(eachrow);
});
filterbind2();
filterbind3();
},'json');
}
What actually is happening is that we are getting a response but it is an empty response. The SQL is ok and runs in MySQL workbench. I have found the following function in php that will display any errors in the json_encode; echo json_last_error_msg(); This shows the following error; "Malformed UTF-8 characters, possibly incorrectly encoded"
This was a massive help! and explained why size wasn't effecting whether or not we got a result and why limiting the results did. There was obviously one row with a character that json_encode didn't like. I found the line in MySQL workbench and I think it was a colon causing the problem. Solved the issue by including a line in the serverside code to set the char set to utf8.
mysqli_set_charset($db,"UTF8");
Where $db is my database connection info

Join two rows which have same value in two column in Ado.Net

For this question, Join two rows which have same value in two column thanks to Jim. But I did not use code in below in windows forms application, concating did not come true. Here is MySQL codes:
SELECT MIN(id),
fikraNo,
maddeNo,
GROUP_CONCAT(icerik ORDER BY id DESC SEPARATOR ' ')
FROM `table`
GROUP BY fikraNo, maddeNo
And here is my searching method which use MySQL:
public static DataTable Results(string table, string columns, string words)
{
var sb = new StringBuilder();
//var pm = new SqlParameter();
sb.Append("SELECT MIN(id) AS minID, name, surname, GROUP_CONCAT(events ORDER BY id ASC SEPARATOR ' ') AS allEvents FROM " + table + " ");
if (!string.IsNullOrEmpty(words))
{
var column = columns.Split('+');
for (var i = 0; i < column.Length; i++)
{
if (i == 0)
{
var word = words.Split(',');
for (var j = 0; j < word.Length; j++)
{
if (j == 0)
{
// one column, one word...
sb.Append("WHERE " + column[i].Trim() + " LIKE '%" + Strip(word[j].Trim()) + "%'");
//pm = new SqlParameter("#word", "%" + word[j].Trim() + "%");
}
else
{
// one column, more words..
sb.Append(" OR " + column[i].Trim() + " LIKE '%" + Strip(word[j].Trim()) + "%'");
//pm = new SqlParameter("#word", "%" + word[j].Trim() + "%");
}
}
}
else
{
var word = words.Split(',');
for (var j = 0; j < word.Length; j++)
{
if (j == 0)
{
// more columns, one word...
sb.Append(" OR " + column[i].Trim() + " LIKE '%" + Strip(word[j].Trim()) + "%'");
//pm = new SqlParameter("#word", "%" + word[j].Trim() + "%");
}
else
{
// more columns, more words...
sb.Append(" OR " + column[i].Trim() + " LIKE '%" + Strip(word[j].Trim()) + "%'");
//pm = new SqlParameter("#word", "%" + word[j].Trim() + "%");
}
}
}
}
}
sb.Append(" GROUP BY name, surname");
var dt = SetDataset(CommandType.Text, sb.ToString(), null).Tables[0];
return dt;
}
But, unfortunately my method only bring first row.
Could you help me, how can I manage it?
King regards.