Concatenate regarding if variables - javascript

so most of my coding is done however as some variables cannot be provided (undefined jQuery results)
the layout of the concatenation string will need to be dynamic and not static
eg. if there is no street number it should pass that variable and continue, and not insert the line breaks.
Current code (added commas to assist with Result explanation):
document.getElementById('fulla').value= streetNumber + ",\n" + streetName + ",\n" + suburb + ",\n" + city + ",\n" + state + ",\n" + country + ",\n" + zip;
Result:
null,<br>
Unnamed Road,<br>
Mabeskraal,<br>
null,<br>
North West,<br>
South Africa,<br>
0313<br>
So what I want it to do is just provide me with the rest without the null Value:
Unnamed Road,<br>
Mabeskraal,<br>
North West,<br>
South Africa,<br>
0313

Get a little more control and save some repetition by stuffing everything into an array:
var addrLines = [streetNumber, streetName, suburb, city, state, country, zip];
filtering away the nulls:
addrLines = addrLines.filter(function(line){return line!=null});
and joining what's left
var addr = addrLines.join("\n");

Related

Receiving String saved wrong in the database

I have an API using Express.js that receives data from Sigfox(A service for IoT) and inserts the data into the SQL Server Express database, this data comes in 4 different URL with this format:
http://servername:port/api/mediciones/sigfox_libelium/aire/2059E7/230934644ae17a8441/1626762070/9
My solution to insert all the data, is to create an array and fill it with the parsed data from the all 4 URL.
[
'2059E7',
64,
16.559999465942383,
98.3505859375,
100161.21875,
1.7199997901916504,
3.1599998474121094,
16.219999313354492
]
When the last request comes and the array is filled, an Insert is made into the database table:
.query("INSERT INTO medicionAire(fecha,id, bateria, temperatura, humedad, presionatmosferica, pm1, pm2, pm10) VALUES(SYSDATETIME()," + dimensiones[0] + ", "+ dimensiones[1] + ", " + dimensiones[2] + ", " + dimensiones[3] + ", " + dimensiones[4] + ", " + dimensiones[5] + ", " + dimensiones[6] + ", " + dimensiones[7] + ");")
where Dimensiones[] is the array filled with data.
ID should be "2059E7" like in the URL but when saved looks like this
EDIT: This is the Design of the table, column id is a Varchar, not a num, but looks like is being treated as a number
In your database the data type of id is a numeric type (float, int, decimal...) and therefore the value 2059E7, which is a mathematical notation for 2059 multiplied by 10000000 (7 zeroes).
SQL server returns a standard notation x.yEz or 2.059E+10.
You need to change the data type of the id column to be a text type (VARCHAR...)

iIf the number is not a number, show the message again. In JS

I have This code
let firstname = window.prompt('Enter ur Firstname');
let lastname = window.prompt('Enter ur Lastname');
let age = window.prompt('Enter ur Age');
console.log('Hello' + firstname + lastname + ' ' + 'and your age is' + ' ' + age);
But in the "Age" section, the user can also enter a string.
What can I do to prevent the user from creating a string?
For example:
User entered a string.
Show message titled "Age entered is not a number"
And the message is displayed again until the user enters a number.
Thank you for helping me ...
You need some sort of loop, to keep taking you back to the age input
The simplest way to structure this is with a while loop. You can test each time, whether age is valid. For simplicity, I am simply testing whether it is greater than 0. This means that 0, although a number, will be rejected, as it is unlikely that a person is actually aged 0 and yet somehow answering the question.
If you are using a while loop, you need to set up a value for age in advance, which you know to be invalid. That will allow the while to test the condition on the first go of the loop, and see that it is not valid, and ask the age.
The code below accepts any number greater than 0 as a valid age.
I've also added a little piece of code that creates an error message that can be fed back to the user.
let firstname = window.prompt('Enter ur Firstname');
let lastname = window.prompt('Enter ur Lastname');
let age = "invalid"
let errorMessage = ""
while (!(age > 0)) {
age = window.prompt(errorMessage + 'Enter ur Age');
errorMessage = '"' + age + '" is not a number. '
}
console.log('Hello' + firstname + ' ' + lastname + ' ' + 'and your age is' + ' ' + age);

Getting column names in SQL query

How can I access column's from SELECT, in my WHERE statement? I'm probably missing quotes. For context, this is in a controller, in Strapi CMS, which runs on a node.js server.
Problem:
Occurs at AND statement (mainly the first st_geomfromtext line):
const rawBuilder = strapi.connections.default.raw(
`
SELECT
locations.id as Location_ID,
locations.Title as Location_Title,
locations.Latitude as Location_Latitude,
locations.Longitude as Location_Longitude,
things.id,
things.Title,
things.Location
FROM locations
RIGHT JOIN things
ON locations.id = things.Location
WHERE things.Style = ` + ctx.query['Style.id'] + `
AND round(st_distance_sphere(
st_geomfromtext(CONCAT('POINT(',locations.Longitude, ' ', locations.Latitude,')')),
st_geomfromtext(CONCAT('POINT(` + ctx.query.Longitude + ` ` + ctx.query.Latitude + `)'))
)) <= ` + 5000
)
Test works:
Just for fun, same as above, but just passed request variables for both st_geomfromtext lines, and the response works; no SQL error:
AND round(st_distance_sphere(
st_geomfromtext(CONCAT('POINT(` + ctx.query.Longitude1 + ` ` + ctx.query.Latitude1 + `)')),
st_geomfromtext(CONCAT('POINT(` + ctx.query.Longitude2 + ` ` + ctx.query.Latitude2 + `)'))
)) <= ` + 5000
So as far as I can tell, the first st_geomfromtext line is the culprit, however it (the 1st line) works fine in a Go server... another clue that this is just a syntax problem.
Below is a working example in SQL Server that should help you resolve this.
Please try these steps:
Remove the "AND" statement from your where clause and save it somewhere
Add some filter criteria that will give you just few known locations
Add new output fields in your select criteria for each function so you will know what you are comparing.
Select CONCAT('POINT(',locations.Longitude, ' ', locations.Latitude,')') from locations
Select st_geomfromtext(CONCAT('POINT(',locations.Longitude, ' ', locations.Latitude,')')) from locations
Note: the output to the geo functions this will probably look cryptic like 0xE6100000010C75931804564253C042CF66D5E7724340
Once the values line up the way you expect then add a new version of the where clause with the adjustments you have made.
Check the precision of the st_distance_sphere function. In SQL Server this is defaulted to meters.
Example in SQL Server
CREATE TABLE #locations (id INT, Title VARCHAR(50), Latitude DECIMAL(10,4), Longitude DECIMAL(10,4))
CREATE TABLE #things (id INT, Title VARCHAR(50), LocationId INT)
INSERT INTO #locations (id, Title, Latitude, Longitude) Values (1,'WH', 38.8977, -77.0365)
INSERT INTO #locations (id, Title, Latitude, Longitude) Values (2,'CB', 38.8899, -77.0091)
INSERT INTO #things (id, Title, LocationId) Values (100,'White House',1)
INSERT INTO #things (id, Title, LocationId) Values (101,'United States Capitol',2)
--My Location at the Washington Monument
DECLARE #myLat DECIMAL(10,4) = 38.8895;
DECLARE #myLong DECIMAL(10,4) = -77.0353
SELECT
loc.id as Location_ID,
loc.Title as Location_Title,
loc.Latitude as Location_Latitude,
loc.Longitude as Location_Longitude,
th.id,
th.Title,
th.LocationId,
geometry::STGeomFromText(CONCAT('POINT(',loc.Longitude, ' ', loc.Latitude,')'),4326) as ItemPoint,
geometry::STGeomFromText(CONCAT('POINT(',#myLat,' ',#myLong,')'),4326) as MyPoint,
geometry::STGeomFromText(CONCAT('POINT(',loc.Longitude, ' ', loc.Latitude,')'),4326).STDistance(geometry::STGeomFromText(CONCAT('POINT(',#myLat,' ',#myLong,')'),4326))
FROM #locations loc
RIGHT JOIN #things th ON loc.id = th.LocationId
DROP TABLE #locations
DROP TABLE #things

mysql parse error shows when query has 3 conditions

i have a select query to a local database and for some reason the following error shows up:
ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'FROM site WHERE name = OCC AND date_start = 2018-07-30 08:00:00 AND date_end = '' at line 1
here's my query:
connection.query("SELECT *, FROM shop WHERE name = " + shop_name + " AND date_start = " + myDate + " AND date_end = " + myDate2, function (err, result)
{
if (err)
{
console.log("Error Is:" + err);
}
else
{
console.log('DATA EXISTING IS =' + JSON.stringify(result));
}
});
am i missing something?
The usual mantra: use parameterized queries. They will prevent SQL injections and make your service more secure. Furthermore they will take care of the usual pitfalls when building a query using string concatenation.
Let's have a look at your query
"SELECT *, FROM shop WHERE name = " + shop_name + " AND date_start = " + myDate + " AND date_end = " + myDate2
Which spells out to something like
SELECT *, FROM shop WHERE name = myshop AND date_start = 2018-07-30 AND date_end = 2018-08-10
There are at least 3 errors
The , behind the SELECT * this is also the one the error tells you about. I suppose you had a column list and replaced it with *
The shop name column is most certainly some char column. So you have to enclose your values with quotes
Also the dates must be used with quotes, so the SQL engine will parse it to a date and do the comparison. For some SQL engines there is also a special annotation for dates. Have a look in the documentation.
This query should work
"SELECT * FROM shop WHERE name = '" + shop_name + "' AND date_start = '" + myDate + "' AND date_end = '" + myDate2 +"'"
depending on what myDate and myDate2 are.
At least problems 2 and 3 would not happen if you use parameterized queries. Consult the documentation of the library you are using.

Javascript variable, different values, same line

First of all, let me apologize for the title, as it isn't so explanatory, but I could not say it in another way.
The deal is: I am doing a javascript application, in which I have an object called "ocorrencia", which was defined like this:
var ocorrencia = new Object();
that object has several children, being filled by a method:
ocorrencia.idOcorrencia = ""+ year + month + day + hour + minute + second + milisec;
idOcorrencia is the one I am having problems with, because I am running a DataBase insert with this value, and I use it 2 times in the same insert, like:
var sql = 'INSERT INTO OCORRENCIAS (id, ocorrencia, data, resolucao, urgencia, foto) VALUES (' + ocorrencia.idOcorrencia + ', "' + ocorrencia.descricao + '", "' + ocorrencia.data + '", "' + ocorrencia.resolucao + '", "' + ocorrencia.grauUrg + '", "' + ocorrencia.idOcorrencia + '.jpg"' +')';
The insert runs great, an I have all the data inserted in the DB, BUT "id" and "foto" (which were supposed to get equal values) are giving me different values by 2 or 3 miliseconds.
How can this happen, as I am not changing "ocorrencia.idOcorrencia" ?
This is beeing tested in an Android device.
EDIT: Tested on Windows browser and the problem doesn't appear to happen.
Thank you
I guess you fill idOcorrencia on runtime? So the lag is producing this difference.
Try using a hash for the id or set it before running the SQL-query.

Categories

Resources