Why is my node database query not working
new at ndoe and mysql interactions, I am trying to get the data of a collunm in my query, what I've done so far:
groupmemberlist is an array of arrays that I am looping in to get each of the values.
%%EDIT%%
I have add these changes but still only get undefined on my variables:
for (var m = 0; m < groupmemberlist.length; m++) {
var imgreturned = findpicture(groupmemberlist[m], returnimage);
console.log(imgtag);
}
This loop can the function findpicture that is:
function returnimage(imgid) {
imgtag = '<img href="/uploads/' + imgid[0].User_Profile_Photo + ">";
}
function findpicture(id, callback) {
return new Promise(function (resolve, reject) {
db.query('SELECT User_Profile_Photo FROM users WHERE id = ?', [id], function (error, results, fields) {
if (error) {
throw error;
} else {
imgFromId = results;
}
callback(imgFromId);
});
})
}
the error that I get is (repeat 4 times):
Query {
domain: null,
_events:
{ error: [Function],
packet: [Function],
end: [Function],
timeout: [Function],
'start-tls': [Function] },
_eventsCount: 5,
_maxListeners: undefined,
_callback: [Function],
_callSite: Error
at Protocol._enqueue (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibprotocolProtocol.js:144:48)
at Connection.query (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibConnection.js:200:25)
at findpicture (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccroutesindex.js:210:31)
at Query.<anonymous> (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccroutesindex.js:232:35)
at Query.<anonymous> (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibConnection.js:502:10)
at Query._callback (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibConnection.js:468:16)
at Query.Sequence.end (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibprotocolsequencesSequence.js:83:24)
at Query._handleFinalResultPacket (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibprotocolsequencesQuery.js:139:8)
at Query.EofPacket (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibprotocolsequencesQuery.js:123:8)
at Protocol._parsePacket (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibprotocolProtocol.js:278:23),
_ended: false,
_timeout: undefined,
_timer: Timer { _object: [Circular], _timeout: null },
sql: 'SELECT User_Profile_Photo FROM users WHERE id = 6 ',
values: [ 6 ],
typeCast: true,
nestTables: false,
_resultSet: null,
_results: ,
_fields: ,
_index: 0,
_loadError: null,
_connection:
Connection {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
config:
ConnectionConfig {
host: '127.0.0.1',
port: 3306,
localAddress: undefined,
socketPath: undefined,
user: 'root',
password: undefined,
database: 'express-cc',
connectTimeout: 10000,
insecureAuth: false,
supportBigNumbers: false,
bigNumberStrings: false,
dateStrings: false,
debug: undefined,
trace: true,
stringifyObjects: false,
timezone: 'local',
flags: '',
queryFormat: undefined,
pool: undefined,
ssl: false,
multipleStatements: false,
typeCast: true,
maxPacketSize: 0,
charsetNumber: 33,
clientFlags: 455631,
protocol41: true },
_socket:
Socket {
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: null,
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 5,
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
_bytesDispatched: 151,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: null,
_server: null,
_idleTimeout: -1,
_idleNext: null,
_idlePrev: null,
_idleStart: 9257,
_destroyed: false,
[Symbol(asyncId)]: 44,
[Symbol(bytesRead)]: 0,
[Symbol(asyncId)]: 47,
[Symbol(triggerAsyncId)]: 10 },
_protocol:
Protocol {
domain: null,
_events: [Object],
_eventsCount: 6,
_maxListeners: undefined,
readable: true,
writable: true,
_config: [Object],
_connection: [Circular],
_callback: null,
_fatalError: null,
_quitSequence: null,
_handshake: true,
_handshaked: true,
_ended: false,
_destroyed: false,
_queue: [Array],
_handshakeInitializationPacket: [Object],
_parser: [Object] },
_connectCalled: true,
state: 'authenticated',
threadId: 767 } }
I also try say var imgname = (results[0].User_Profile_Photo) inside the query function and try console.log the var imgname but it return error of var undefined.
javascript mysql node.js
add a comment |
new at ndoe and mysql interactions, I am trying to get the data of a collunm in my query, what I've done so far:
groupmemberlist is an array of arrays that I am looping in to get each of the values.
%%EDIT%%
I have add these changes but still only get undefined on my variables:
for (var m = 0; m < groupmemberlist.length; m++) {
var imgreturned = findpicture(groupmemberlist[m], returnimage);
console.log(imgtag);
}
This loop can the function findpicture that is:
function returnimage(imgid) {
imgtag = '<img href="/uploads/' + imgid[0].User_Profile_Photo + ">";
}
function findpicture(id, callback) {
return new Promise(function (resolve, reject) {
db.query('SELECT User_Profile_Photo FROM users WHERE id = ?', [id], function (error, results, fields) {
if (error) {
throw error;
} else {
imgFromId = results;
}
callback(imgFromId);
});
})
}
the error that I get is (repeat 4 times):
Query {
domain: null,
_events:
{ error: [Function],
packet: [Function],
end: [Function],
timeout: [Function],
'start-tls': [Function] },
_eventsCount: 5,
_maxListeners: undefined,
_callback: [Function],
_callSite: Error
at Protocol._enqueue (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibprotocolProtocol.js:144:48)
at Connection.query (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibConnection.js:200:25)
at findpicture (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccroutesindex.js:210:31)
at Query.<anonymous> (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccroutesindex.js:232:35)
at Query.<anonymous> (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibConnection.js:502:10)
at Query._callback (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibConnection.js:468:16)
at Query.Sequence.end (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibprotocolsequencesSequence.js:83:24)
at Query._handleFinalResultPacket (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibprotocolsequencesQuery.js:139:8)
at Query.EofPacket (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibprotocolsequencesQuery.js:123:8)
at Protocol._parsePacket (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibprotocolProtocol.js:278:23),
_ended: false,
_timeout: undefined,
_timer: Timer { _object: [Circular], _timeout: null },
sql: 'SELECT User_Profile_Photo FROM users WHERE id = 6 ',
values: [ 6 ],
typeCast: true,
nestTables: false,
_resultSet: null,
_results: ,
_fields: ,
_index: 0,
_loadError: null,
_connection:
Connection {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
config:
ConnectionConfig {
host: '127.0.0.1',
port: 3306,
localAddress: undefined,
socketPath: undefined,
user: 'root',
password: undefined,
database: 'express-cc',
connectTimeout: 10000,
insecureAuth: false,
supportBigNumbers: false,
bigNumberStrings: false,
dateStrings: false,
debug: undefined,
trace: true,
stringifyObjects: false,
timezone: 'local',
flags: '',
queryFormat: undefined,
pool: undefined,
ssl: false,
multipleStatements: false,
typeCast: true,
maxPacketSize: 0,
charsetNumber: 33,
clientFlags: 455631,
protocol41: true },
_socket:
Socket {
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: null,
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 5,
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
_bytesDispatched: 151,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: null,
_server: null,
_idleTimeout: -1,
_idleNext: null,
_idlePrev: null,
_idleStart: 9257,
_destroyed: false,
[Symbol(asyncId)]: 44,
[Symbol(bytesRead)]: 0,
[Symbol(asyncId)]: 47,
[Symbol(triggerAsyncId)]: 10 },
_protocol:
Protocol {
domain: null,
_events: [Object],
_eventsCount: 6,
_maxListeners: undefined,
readable: true,
writable: true,
_config: [Object],
_connection: [Circular],
_callback: null,
_fatalError: null,
_quitSequence: null,
_handshake: true,
_handshaked: true,
_ended: false,
_destroyed: false,
_queue: [Array],
_handshakeInitializationPacket: [Object],
_parser: [Object] },
_connectCalled: true,
state: 'authenticated',
threadId: 767 } }
I also try say var imgname = (results[0].User_Profile_Photo) inside the query function and try console.log the var imgname but it return error of var undefined.
javascript mysql node.js
Tryvar imgname = results[0].user_profile_photo;
. MySQL may be downcasing the column names it returns. Or, tryconsole.log(fields);
to see a description of the fields (columns) in the result set.
– O. Jones
Nov 22 '18 at 22:31
add a comment |
new at ndoe and mysql interactions, I am trying to get the data of a collunm in my query, what I've done so far:
groupmemberlist is an array of arrays that I am looping in to get each of the values.
%%EDIT%%
I have add these changes but still only get undefined on my variables:
for (var m = 0; m < groupmemberlist.length; m++) {
var imgreturned = findpicture(groupmemberlist[m], returnimage);
console.log(imgtag);
}
This loop can the function findpicture that is:
function returnimage(imgid) {
imgtag = '<img href="/uploads/' + imgid[0].User_Profile_Photo + ">";
}
function findpicture(id, callback) {
return new Promise(function (resolve, reject) {
db.query('SELECT User_Profile_Photo FROM users WHERE id = ?', [id], function (error, results, fields) {
if (error) {
throw error;
} else {
imgFromId = results;
}
callback(imgFromId);
});
})
}
the error that I get is (repeat 4 times):
Query {
domain: null,
_events:
{ error: [Function],
packet: [Function],
end: [Function],
timeout: [Function],
'start-tls': [Function] },
_eventsCount: 5,
_maxListeners: undefined,
_callback: [Function],
_callSite: Error
at Protocol._enqueue (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibprotocolProtocol.js:144:48)
at Connection.query (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibConnection.js:200:25)
at findpicture (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccroutesindex.js:210:31)
at Query.<anonymous> (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccroutesindex.js:232:35)
at Query.<anonymous> (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibConnection.js:502:10)
at Query._callback (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibConnection.js:468:16)
at Query.Sequence.end (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibprotocolsequencesSequence.js:83:24)
at Query._handleFinalResultPacket (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibprotocolsequencesQuery.js:139:8)
at Query.EofPacket (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibprotocolsequencesQuery.js:123:8)
at Protocol._parsePacket (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibprotocolProtocol.js:278:23),
_ended: false,
_timeout: undefined,
_timer: Timer { _object: [Circular], _timeout: null },
sql: 'SELECT User_Profile_Photo FROM users WHERE id = 6 ',
values: [ 6 ],
typeCast: true,
nestTables: false,
_resultSet: null,
_results: ,
_fields: ,
_index: 0,
_loadError: null,
_connection:
Connection {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
config:
ConnectionConfig {
host: '127.0.0.1',
port: 3306,
localAddress: undefined,
socketPath: undefined,
user: 'root',
password: undefined,
database: 'express-cc',
connectTimeout: 10000,
insecureAuth: false,
supportBigNumbers: false,
bigNumberStrings: false,
dateStrings: false,
debug: undefined,
trace: true,
stringifyObjects: false,
timezone: 'local',
flags: '',
queryFormat: undefined,
pool: undefined,
ssl: false,
multipleStatements: false,
typeCast: true,
maxPacketSize: 0,
charsetNumber: 33,
clientFlags: 455631,
protocol41: true },
_socket:
Socket {
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: null,
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 5,
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
_bytesDispatched: 151,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: null,
_server: null,
_idleTimeout: -1,
_idleNext: null,
_idlePrev: null,
_idleStart: 9257,
_destroyed: false,
[Symbol(asyncId)]: 44,
[Symbol(bytesRead)]: 0,
[Symbol(asyncId)]: 47,
[Symbol(triggerAsyncId)]: 10 },
_protocol:
Protocol {
domain: null,
_events: [Object],
_eventsCount: 6,
_maxListeners: undefined,
readable: true,
writable: true,
_config: [Object],
_connection: [Circular],
_callback: null,
_fatalError: null,
_quitSequence: null,
_handshake: true,
_handshaked: true,
_ended: false,
_destroyed: false,
_queue: [Array],
_handshakeInitializationPacket: [Object],
_parser: [Object] },
_connectCalled: true,
state: 'authenticated',
threadId: 767 } }
I also try say var imgname = (results[0].User_Profile_Photo) inside the query function and try console.log the var imgname but it return error of var undefined.
javascript mysql node.js
new at ndoe and mysql interactions, I am trying to get the data of a collunm in my query, what I've done so far:
groupmemberlist is an array of arrays that I am looping in to get each of the values.
%%EDIT%%
I have add these changes but still only get undefined on my variables:
for (var m = 0; m < groupmemberlist.length; m++) {
var imgreturned = findpicture(groupmemberlist[m], returnimage);
console.log(imgtag);
}
This loop can the function findpicture that is:
function returnimage(imgid) {
imgtag = '<img href="/uploads/' + imgid[0].User_Profile_Photo + ">";
}
function findpicture(id, callback) {
return new Promise(function (resolve, reject) {
db.query('SELECT User_Profile_Photo FROM users WHERE id = ?', [id], function (error, results, fields) {
if (error) {
throw error;
} else {
imgFromId = results;
}
callback(imgFromId);
});
})
}
the error that I get is (repeat 4 times):
Query {
domain: null,
_events:
{ error: [Function],
packet: [Function],
end: [Function],
timeout: [Function],
'start-tls': [Function] },
_eventsCount: 5,
_maxListeners: undefined,
_callback: [Function],
_callSite: Error
at Protocol._enqueue (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibprotocolProtocol.js:144:48)
at Connection.query (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibConnection.js:200:25)
at findpicture (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccroutesindex.js:210:31)
at Query.<anonymous> (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccroutesindex.js:232:35)
at Query.<anonymous> (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibConnection.js:502:10)
at Query._callback (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibConnection.js:468:16)
at Query.Sequence.end (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibprotocolsequencesSequence.js:83:24)
at Query._handleFinalResultPacket (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibprotocolsequencesQuery.js:139:8)
at Query.EofPacket (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibprotocolsequencesQuery.js:123:8)
at Protocol._parsePacket (C:Usersyvyma.DESKTOP-74AK6UQDesktopNodeappexpress-ccnode_modulesmysqllibprotocolProtocol.js:278:23),
_ended: false,
_timeout: undefined,
_timer: Timer { _object: [Circular], _timeout: null },
sql: 'SELECT User_Profile_Photo FROM users WHERE id = 6 ',
values: [ 6 ],
typeCast: true,
nestTables: false,
_resultSet: null,
_results: ,
_fields: ,
_index: 0,
_loadError: null,
_connection:
Connection {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
config:
ConnectionConfig {
host: '127.0.0.1',
port: 3306,
localAddress: undefined,
socketPath: undefined,
user: 'root',
password: undefined,
database: 'express-cc',
connectTimeout: 10000,
insecureAuth: false,
supportBigNumbers: false,
bigNumberStrings: false,
dateStrings: false,
debug: undefined,
trace: true,
stringifyObjects: false,
timezone: 'local',
flags: '',
queryFormat: undefined,
pool: undefined,
ssl: false,
multipleStatements: false,
typeCast: true,
maxPacketSize: 0,
charsetNumber: 33,
clientFlags: 455631,
protocol41: true },
_socket:
Socket {
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: null,
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 5,
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
_bytesDispatched: 151,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: null,
_server: null,
_idleTimeout: -1,
_idleNext: null,
_idlePrev: null,
_idleStart: 9257,
_destroyed: false,
[Symbol(asyncId)]: 44,
[Symbol(bytesRead)]: 0,
[Symbol(asyncId)]: 47,
[Symbol(triggerAsyncId)]: 10 },
_protocol:
Protocol {
domain: null,
_events: [Object],
_eventsCount: 6,
_maxListeners: undefined,
readable: true,
writable: true,
_config: [Object],
_connection: [Circular],
_callback: null,
_fatalError: null,
_quitSequence: null,
_handshake: true,
_handshaked: true,
_ended: false,
_destroyed: false,
_queue: [Array],
_handshakeInitializationPacket: [Object],
_parser: [Object] },
_connectCalled: true,
state: 'authenticated',
threadId: 767 } }
I also try say var imgname = (results[0].User_Profile_Photo) inside the query function and try console.log the var imgname but it return error of var undefined.
javascript mysql node.js
javascript mysql node.js
edited Nov 24 '18 at 19:38
Vinícius Maia Silveira
asked Nov 22 '18 at 22:20
Vinícius Maia SilveiraVinícius Maia Silveira
13
13
Tryvar imgname = results[0].user_profile_photo;
. MySQL may be downcasing the column names it returns. Or, tryconsole.log(fields);
to see a description of the fields (columns) in the result set.
– O. Jones
Nov 22 '18 at 22:31
add a comment |
Tryvar imgname = results[0].user_profile_photo;
. MySQL may be downcasing the column names it returns. Or, tryconsole.log(fields);
to see a description of the fields (columns) in the result set.
– O. Jones
Nov 22 '18 at 22:31
Try
var imgname = results[0].user_profile_photo;
. MySQL may be downcasing the column names it returns. Or, try console.log(fields);
to see a description of the fields (columns) in the result set.– O. Jones
Nov 22 '18 at 22:31
Try
var imgname = results[0].user_profile_photo;
. MySQL may be downcasing the column names it returns. Or, try console.log(fields);
to see a description of the fields (columns) in the result set.– O. Jones
Nov 22 '18 at 22:31
add a comment |
1 Answer
1
active
oldest
votes
Your code is all kinds of messed up. You have some things out of place. Here's a better, though not perfect, version:
function findpicture(id) {
let imgFromId;
db.query('SELECT User_Profile_Photo FROM users WHERE id = ?', [id], function (error, results, fields) {
if (error) {
throw error;
}
imgFromId = results;
console.log(imgfromid);
});
}
Now, lets explain what's wrong with your code. It'll provide you some good concepts to understand.
db.query
is using a callback function. This means that its an asyncronous
request. That means that the results take some time to come back. What you're trying to do right now by assigning db.query
to imgFromId
is not getting the results of your query, but just assigning a reference to whatever comes back from db.query
.
In the corrected version I shared, you need to define imgFromId
outside of the callback function. When the results return, you assign the results to that inside the callback function.
However, this will still not fix your issue. Since you're dealing with asyncronous code you need to look into Promises and async/await.
I understand, but I am still struggling with it, what I have so far now:
– Vinícius Maia Silveira
Nov 24 '18 at 2:27
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53438601%2fwhy-is-my-node-database-query-not-working%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Your code is all kinds of messed up. You have some things out of place. Here's a better, though not perfect, version:
function findpicture(id) {
let imgFromId;
db.query('SELECT User_Profile_Photo FROM users WHERE id = ?', [id], function (error, results, fields) {
if (error) {
throw error;
}
imgFromId = results;
console.log(imgfromid);
});
}
Now, lets explain what's wrong with your code. It'll provide you some good concepts to understand.
db.query
is using a callback function. This means that its an asyncronous
request. That means that the results take some time to come back. What you're trying to do right now by assigning db.query
to imgFromId
is not getting the results of your query, but just assigning a reference to whatever comes back from db.query
.
In the corrected version I shared, you need to define imgFromId
outside of the callback function. When the results return, you assign the results to that inside the callback function.
However, this will still not fix your issue. Since you're dealing with asyncronous code you need to look into Promises and async/await.
I understand, but I am still struggling with it, what I have so far now:
– Vinícius Maia Silveira
Nov 24 '18 at 2:27
add a comment |
Your code is all kinds of messed up. You have some things out of place. Here's a better, though not perfect, version:
function findpicture(id) {
let imgFromId;
db.query('SELECT User_Profile_Photo FROM users WHERE id = ?', [id], function (error, results, fields) {
if (error) {
throw error;
}
imgFromId = results;
console.log(imgfromid);
});
}
Now, lets explain what's wrong with your code. It'll provide you some good concepts to understand.
db.query
is using a callback function. This means that its an asyncronous
request. That means that the results take some time to come back. What you're trying to do right now by assigning db.query
to imgFromId
is not getting the results of your query, but just assigning a reference to whatever comes back from db.query
.
In the corrected version I shared, you need to define imgFromId
outside of the callback function. When the results return, you assign the results to that inside the callback function.
However, this will still not fix your issue. Since you're dealing with asyncronous code you need to look into Promises and async/await.
I understand, but I am still struggling with it, what I have so far now:
– Vinícius Maia Silveira
Nov 24 '18 at 2:27
add a comment |
Your code is all kinds of messed up. You have some things out of place. Here's a better, though not perfect, version:
function findpicture(id) {
let imgFromId;
db.query('SELECT User_Profile_Photo FROM users WHERE id = ?', [id], function (error, results, fields) {
if (error) {
throw error;
}
imgFromId = results;
console.log(imgfromid);
});
}
Now, lets explain what's wrong with your code. It'll provide you some good concepts to understand.
db.query
is using a callback function. This means that its an asyncronous
request. That means that the results take some time to come back. What you're trying to do right now by assigning db.query
to imgFromId
is not getting the results of your query, but just assigning a reference to whatever comes back from db.query
.
In the corrected version I shared, you need to define imgFromId
outside of the callback function. When the results return, you assign the results to that inside the callback function.
However, this will still not fix your issue. Since you're dealing with asyncronous code you need to look into Promises and async/await.
Your code is all kinds of messed up. You have some things out of place. Here's a better, though not perfect, version:
function findpicture(id) {
let imgFromId;
db.query('SELECT User_Profile_Photo FROM users WHERE id = ?', [id], function (error, results, fields) {
if (error) {
throw error;
}
imgFromId = results;
console.log(imgfromid);
});
}
Now, lets explain what's wrong with your code. It'll provide you some good concepts to understand.
db.query
is using a callback function. This means that its an asyncronous
request. That means that the results take some time to come back. What you're trying to do right now by assigning db.query
to imgFromId
is not getting the results of your query, but just assigning a reference to whatever comes back from db.query
.
In the corrected version I shared, you need to define imgFromId
outside of the callback function. When the results return, you assign the results to that inside the callback function.
However, this will still not fix your issue. Since you're dealing with asyncronous code you need to look into Promises and async/await.
answered Nov 22 '18 at 23:01
GeuisGeuis
19.6k45119194
19.6k45119194
I understand, but I am still struggling with it, what I have so far now:
– Vinícius Maia Silveira
Nov 24 '18 at 2:27
add a comment |
I understand, but I am still struggling with it, what I have so far now:
– Vinícius Maia Silveira
Nov 24 '18 at 2:27
I understand, but I am still struggling with it, what I have so far now:
– Vinícius Maia Silveira
Nov 24 '18 at 2:27
I understand, but I am still struggling with it, what I have so far now:
– Vinícius Maia Silveira
Nov 24 '18 at 2:27
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53438601%2fwhy-is-my-node-database-query-not-working%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Try
var imgname = results[0].user_profile_photo;
. MySQL may be downcasing the column names it returns. Or, tryconsole.log(fields);
to see a description of the fields (columns) in the result set.– O. Jones
Nov 22 '18 at 22:31