I'm using Node.js together with mysql, express and html.
When I'm retrieving the results from the database I get the following date,
2016-03-16T00:00:00.000Z, even though the type in mysql is date.
My query:
app.get('/list', function (req,res) {
connection.query('SELECT `ondate`,`projectname`,`hours` FROM `entries` WHERE YEARWEEK(`ondate`, 1) = YEARWEEK(CURDATE(), 1) ORDER BY ondate DESC ,projectname ASC ', function(err, rows, fields) {
res.json({error: err, result: rows});
});
})
Is there a way I can set the ondate field to ignore the time?
Use this:
SELECT
DATE_FORMAT(`ondate`,'%m-%d-%Y'),
`projectname`,
`hours`
FROM `entries`
WHERE YEARWEEK(`ondate`, 1) = YEARWEEK(CURDATE(), 1)
ORDER BY ondate DESC, projectname ASC;
Adjust the date format to the one you need.
Regards
Hard to know exactly where the unwanted formatting is being introduced, but it might be an option to remove it as part of post processing rows...
// Assuming array of rows takes shape something like this...
var rows = [{ondate:'2012-01-02T00:00:00.000Z'},{ondate:'2013-01-02T00:00:00.000Z'},{ondate:'2012-03-02T00:00:00.000Z'}];
// map rows to show only first ten chars of `ondate` field
rows = rows.map(function(item){ return item.ondate.slice(0,10); });
// business as usual...
alert(rows);
//-> 2012-01-02,2013-01-02,2012-03-02
Related
This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
Is the database query faster if I insert multiple rows at once:
like
INSERT....
UNION
INSERT....
UNION
(I need to insert like 2-3000 rows)
INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas.
Example:
INSERT INTO tbl_name
(a,b,c)
VALUES
(1,2,3),
(4,5,6),
(7,8,9);
Source
If you have your data in a text-file, you can use LOAD DATA INFILE.
When loading a table from a text file, use LOAD DATA INFILE. This is usually 20 times faster than using INSERT statements.
Optimizing INSERT Statements
You can find more tips on how to speed up your insert statements on the link above.
Just use a SELECT statement to get the values for many lines of the chosen columns and put these values into columns of another table in one go. As an example, columns "size" and "price" of the two tables "test_b" and "test_c" get filled with the columns "size" and "price" of table "test_a".
BEGIN;
INSERT INTO test_b (size, price)
SELECT size, price
FROM test_a;
INSERT INTO test_c (size, price)
SELECT size, price
FROM test_a;
COMMIT;
The code is embedded in BEGIN and COMMIT to run it only when both statements have worked, else the whole run up to that point gets withdrawn.
Here is a PHP solution ready for use with a n:m (many-to-many relationship) table :
// get data
$table_1 = get_table_1_rows();
$table_2_fk_id = 123;
// prepare first part of the query (before values)
$query = "INSERT INTO `table` (
`table_1_fk_id`,
`table_2_fk_id`,
`insert_date`
) VALUES ";
//loop the table 1 to get all foreign keys and put it in array
foreach($table_1 as $row) {
$query_values[] = "(".$row["table_1_pk_id"].", $table_2_fk_id, NOW())";
}
// Implode the query values array with a coma and execute the query.
$db->query($query . implode(',',$query_values));
EDIT : After #john's comment I decided to enhance this answer with a more efficient solution :
divides the query to multiple smaller queries
use rtrim() to delete last coma instead of implod()
// limit of query size (lines inserted per query)
$query_values = "";
$limit = 100;
$table_1 = get_table_1_rows();
$table_2_fk_id = 123;
$query = "INSERT INTO `table` (
`table_1_fk_id`,
`table_2_fk_id`,
`insert_date`
) VALUES ";
foreach($table_1 as $row) {
$query_values .= "(".$row["table_1_pk_id"].", $table_2_fk_id, NOW()),";
// entire table parsed or lines limit reached :
// -> execute and purge query_values
if($i === array_key_last($table_1)
|| fmod(++$i / $limit) == 0) {
$db->query($query . rtrim($query_values, ','));
$query_values = "";
}
}
// db table name / blog_post / menu / site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO product_cate (site_title, sub_title)
VALUES ('$site_title', '$sub_title')";
// db table name / blog_post / menu / site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO menu (menu_title, sub_menu)
VALUES ('$menu_title', '$sub_menu', )";
// db table name / blog_post / menu / site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO blog_post (post_title, post_des, post_img)
VALUES ('$post_title ', '$post_des', '$post_img')";
I have a page that looks like this:
What I'm trying to do is to compare "Holiday Date:" selection against the row values in "Date" columns from the table below it. I've tried using a code like this:
function dateChk(){
var dt1 = document.getElementById('PHDate').value;
var dt2 = document.getElementById('phdateadd').value;
if (dt1 == dt2) {
alert("This date already assigned, please try again.");
document.getElementById('phdateadd').value = 0;
}
}
But this only work on the first row. Then I thought of doing array like:
<input id="phdateadd" name="phdateadd" type="date" onchange="myFunction()" required>
<p id="demo"></p>
<script>
var dates= ["2021-01-01", "2021-02-12", "2021-02-13", "2021-04-02", "2021-05-01",
"2021-05-13", "2021-05-14", "2021-05-26", "2021-05-30", "2021-05-31",
"2021-07-06", "2021-07-20", "2021-08-10", "2021-08-31", "2021-09-16",
"2021-10-02", "2021-10-19", "2021-11-04", "2021-12-25"];
function checkDate(date) {
return date == document.getElementById("phdateadd").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = dates.find(checkDate);
var chk = document.getElementById("demo").innerHTML;
if ( chk != "undefined" ) {
alert("This date already assigned, please try again.");
document.getElementById("phdateadd").value = 0;}
}
</script>
This does work however I have to specify all the dates from that column as array. I have this idea of passing data from MySQL query with the date values formatted similar to the array but it doesn't seem to recognize. This is the query:
SELECT CONCAT('["',GROUP_CONCAT(phdate SEPARATOR '", "'),'"]') As arrdate FROM table1;
which returns
["2021-01-01", "2021-02-12", "2021-02-13", "2021-04-02", "2021-05-01", "2021-05-13", "2021-05-14",
"2021-05-26", "2021-05-30", "2021-05-31", "2021-07-06", "2021-07-20", "2021-08-10", "2021-08-31",
"2021-09-16", "2021-10-02", "2021-10-19", "2021-11-04", "2021-12-25"]
So, I took that result and show it in the page:
<% phDates.forEach((phDates, index) => { %>
<tr><td><p id="phdates" name="phdates" value="<%= phDates.arrdate %>"><%= phDates.arrdate %>
<% }) %></p><p id="demo" name="demo">b</p><br><p id="demo1" name="demo1">a</p></td></tr>
<script>
var dates = document.getElementById("phdates").innerHTML;
document.getElementById("demo").innerHTML = dates;
</script>
As you can see arrdate values that comes from the MySQL query and demo is showing similar format. The demo value is different when I specify the array in var dates (like in my snippet above):
If I purposely make the MySQL return data as above though it still doesn't recognize it. I think if this method is workable, I don't even need to compare the selected date to the column in the table. I did a test using $( "div" ).toArray() but I can't get it to work either.
I think this could be the straight forward solution for me but I'm wondering how do I format the MySQL result value to correspond with the correct javascript array format? Or leave the MySQL output as it is and convert that value to javascript array compatible value. I can't help to think that the solution might be simple but I've been looking for a couple of days and I haven't found any.
Actually there is a straight-forward solution. Let's start our thought process from your query, which is not very far from the solution (this is not good yet, but it's close-enough to start our thought process from it):
SELECT CONCAT('["',GROUP_CONCAT(phdate SEPARATOR '", "'),'"]') As arrdate FROM table1;
You intend here to convert your data into a JSON-like string. Naturally, you could call JSON.parse or eval with value assignment on this result, but I recommend a much more elegant way:
SELECT GROUP_CONCAT(phdate SEPARATOR ',') As dates FROM table1;
The above will contain a string with dates separated by comma. Assuming that you get this into a JS variable called myDates, you can just call:
myDates.split(",")
let myDates = '2021-01-13,2021-02-02,2021-03-04'; //results from db
console.log(myDates.split(','));
Generate either of these in the WHERE clause of SQL:
arrdate IN ("2021-01-01", "2021-02-12", "2021-02-13")
FIND_IN_SET(arrdate, "2021-01-01,2021-02-12,2021-02-13")
The performance of the first may benefit from a suitable INDEX; the second won't.
If you are trying to check whether any of several dates (or other value) is found in any of a second set of dates -- This is not directly available in MySQL. Split one list (or the other list) into rows in a table, then use IN or FIND_IN_SET().
Or use application code.
So I have this weird issue with node js right now and can not find any solution...
Im trying to insert values to my mssql table and some of the values includes the swedish characters "åäö". Anyhow when I do this they appear as "??????". Each special character appear as two question marks ("ö" -> "??").
Some details:
*Package I'm using is in js: msnodesqlv8
var sql = require('msnodesqlv8');
const connectionString = "server=host;Database=MyDb;Trusted_Connection=Yes;Driver={SQL Server Native Client 11.0}"
q = "Insert into [MyDb].[dbo].[MyTable] (testCol) values ('ö')"
sql.query(connectionString, q, (err,data) => {
if (err) {
console.log(err);
}
else {
console.log('Imported row to table.');
}
})
*The columns in the db table that will retrieve values containing "åäö" is defined as datatype nvarchar(50)
I have also trid with N'ö' in variable q and these characters (within the double quotes) appear in db table "ᅢᄊ"
*console.log('ö') prints ö in console as expected
*I have tried all conversions i can think about in js (for example utf-8, latin1, etc...)
*Collation in db is Finnish_Swedish_CI_AS
*I have tried to read out swedish chrs from another table and it works fine through the package msnodesqlv8
The problem to me seems to be somewhere when sending the query from js (everything looks fine here), through package msnodesqlv8 and when mssql shall interpret the values. Im very glad if someone can help me.
Is there some reason you're not using a prepared statement? It takes care of the encoding for you, e.g.:
const sql = require('msnodesqlv8')
const connectionString = "server=YourServerIp,YourServerPort;Database=StackOverflow;Trusted_Connection=Yes;Driver={SQL Server Native Client 11.0};"
console.log('Connecting...')
sql.open(connectionString, (err, conn) => {
console.log('Dropping...')
conn.query('drop table if exists [dbo].[Swedish]', (err,) => {
console.log('Creating...')
conn.query('create table [dbo].[Swedish] (testCol nvarchar(50))', (err) => {
console.log('Inserting...')
conn.prepare('insert [dbo].[Swedish] (testCol) values (?)', (err, ps) => {
ps.preparedQuery(['ö'], (err) => {
ps.free();
console.log('Selecting...')
conn.query('select * from [dbo].[Swedish]', (err, rows) => {
console.log(`${JSON.stringify(rows)}`)
})
})
})
})
})
})
Which yields...
> node .\swedish.js
Connecting...
Dropping...
Creating...
Inserting...
Selecting...
[{"testCol":"ö"}]
The same character is present when queried via SSMS.
I am trying to set up a google scatter chart page from these links...
https://developers.google.com/chart/interactive/docs/gallery/scatterchart
and create data table here...
https://developers.google.com/chart/interactive/docs/drawing_charts#chart.draw
Basically I have the basic demo copy working.
Now I am trying to populate the data table with time and date data like this...
add rows like this...
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('number', 'Time');
data.addColumn('number', 'Date');
data.addRows([
// this raw text works
[22,5],[10,24],[9,5],[10,6],[10,7],[7,8]
// but my var - datetime from database not working
//Error: Every row given must be either null or an array.
datetime
]);
If I manually type in this:
[22,5],[10,24],[9,5],[10,6],[10,7],[7,8]
it works.
Now I am trying to query a database - then do a .each loop to get the data...
//Query the database...
// query here..
datetime = "";
$.each(data, function(key, value) {
//note: each row comes in from the database like:
//thedate: "02/17/2018" thetime: "18:00:00"
//then I split to just get basic hour and day
t = value.thetime.split(":")
d = value.thedate.split("/")
//and create as numbers
tnum = parseInt(t[0]);
dnum = parseInt(d[1]);
//and add to the datetime var
datetime += "["+ dnum + ","+ tnum + "],"
// there was more code to eliminate last ","
// then the end result var datetime looks something like:
//[22,5],[10,24],[9,5],[10,6],[10,7],[7,8]
If I manually paste this into the add rows area - it works, however if just paste the datetime var into the same add rows area. the error says:
Error: Every row given must be either null or an array.
Q: I'm sure I am missing something basic, such as the graph needs numbers that may be showing as strings or my array is wrong or something else. Is there something to change to get the graph to accept my datetime var?
looks like you're trying to create an array from a string,
instead, use an actual array, which addRows expects...
datetime = [];
$.each(data, function(key, value) {
t = value.thetime.split(":")
d = value.thedate.split("/")
tnum = parseInt(t[0]);
dnum = parseInt(d[1]);
datetime.push([dnum, tnum]);
});
data.addRows(datetime);
I have created a table and sorted it with tablesorter. One of the columns is a mix of letters and numbers (chr1, chr2, ..., chr10, ... , chrM). I want this column to be sorted as if it were only numbers (from 1 to 22 and then X, Y and M in this order).
I have created my own parser and it works but just for some rows. Then, I find another block of rows which are correctly sorted followed by some other blocks. I do not know why this blocks are formed.
The code is here. Maybe with a smaller table it would work properly, because of that I have shown a big one.
Thanks in advance!
Try this parser (demo)
$.tablesorter.addParser({
// set a unique id
id: 'chrom',
is: function (s) {
// return false so this parser is not auto detected
return false;
},
format: function (s) {
// format your data for normalization
return s.toLowerCase()
.replace('chr', '')
.replace('x', '97')
.replace('y', '98')
.replace('m', '99');
},
// set type, either numeric or text
type: 'numeric'
});