Cannot read property 'query' of undefined error: mysql and node.js - mysql

I'm trying to send information from android to mysql database through express server (using node js)
however there seems to be a problem in the code, it keeps showing error, but I just can't find what's wrong.
I think there's problem with connection.query statement.
Actually this is not my code, but it's the source code of my teacher. I checked everything in the android twice, but there's nothing wrong. There's gotta be something wrong here :(
This is what it is keep saying. Please help :( Stock for few days...

When you call the getConnection() method, the callback function passed to it should check for errors first. The reason you're running into the "cannot get property of undefined" error is most likely because the connection object is never returned and therefore undefined, probably because getConnection() encounters an error.
Try adding an error check condition and log the error to see why getConnection() fails:
mysql_connection_info.getConnection(function(err, connection) {
// check for errors in getting the connection
if(err) {
console.log(err)
return
}
// carry on with the actual query if there are no errors
})

I think you are missingmysql_connection_info.connect()
place it just after creating the connection pool.

Related

MYSQL Select db & Select table issue. Configuration confusion [duplicate]

In my local/development environment, the MySQLi query is performing OK. However, when I upload it on my web host environment, I get this error:
Fatal error: Call to a member function bind_param() on a non-object in...
Here is the code:
global $mysqli;
$stmt = $mysqli->prepare("SELECT id, description FROM tbl_page_answer_category WHERE cur_own_id = ?");
$stmt->bind_param('i', $cur_id);
$stmt->execute();
$stmt->bind_result($uid, $desc);
To check my query, I tried to execute the query via control panel phpMyAdmin and the result is OK.
TL;DR
Always have mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); in your mysqli connection code and always check the PHP errors.
Always replace every PHP variable in the SQL query with a question mark, and execute the query using prepared statement. It will help to avoid syntax errors of all sorts.
Explanation
Sometimes your MySQLi code produces an error like mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given..., Call to a member function bind_param()... or similar. Or even without any error, but the query doesn't work all the same. It means that your query failed to execute.
Every time a query fails, MySQL has an error message that explains the reason. In the older PHP versions such errors weren't transferred to PHP, and all you'd get is a cryptic error message mentioned above. Hence it is very important to configure PHP and MySQLi to report MySQL errors to you. And once you get the error message, fixing it will be a piece of cake.
How to get the error message in MySQLi
First of all, always have this line before MySQLi connect in all your environments:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
After that, all MySQL errors will be transferred into PHP exceptions. An uncaught exception, in turn, makes a PHP fatal error. Thus, in case of a MySQL error, you'll get a conventional PHP error. That will instantly make you aware of the error cause. And the stack trace will lead you to the exact spot where the error occurred.
How to get the error message from PHP
Here is a gist of my article on PHP error reporting:
Reporting errors on a development and live servers must be different. On the development server it is convenient to have errors shown on-screen, but on a live server error messages must be logged instead, so you could find them in the error log later.
Therefore, you must set corresponding configuration options to the following values:
On a development server
error_reporting should be set to E_ALL value;
log_errors should be set to 1 (it is convenient to have logs on a development PC too)
display_errors should be set to 1
On a production server
error_reporting should be set to E_ALL value;
log_errors should be set to 1
display_errors should be set to 0
After that, when MySQL query fails, you will get a PHP error that explains the reason. On a live server, in order to get the error message, you'll have to check the error log.
In case of AJAX call, on a dev server open DevTools (F12), then Network tab. Then initiate the request which result you want to see, and it will appear in the Network tab. Click on it and then the Response tab. There you will see the exact output. On a live server check the error log.
How to actually use it
Just remove any code that checks for the error manually, all those or die(), if ($result), try..catch and such. Simply write your database interaction code right away:
$stmt = $this->con->prepare("INSERT INTO table(name, quantity) VALUES (?,?)");
$stmt->bind_param("si", $name, $quantity);
$stmt->execute();
Again, without any conditions around. If an error occurs, it will be treated like any other error in your code. For example, on a development PC it will just appear on-screen, while on a live site it will be logged for the programmer, whereas for the user's convenience you could use an error handler (but that's a different story which is off topic for MySQLi, but you may read about it in the article linked above).
What to do with the error message you get
First of all you have to locate the problem query. The error message contains the file name and the line number of the exact spot where the error occurred. For the simple code that's enough, but if your code is using functions or classes you may need to follow the stack trace to locate the problem query.
After getting the error message, you have to read and comprehend it. It sounds too obvious if not condescending, but learners often overlook the fact that the error message is not just an alarm signal, but it actually contains a detailed explanation of the problem. And all you need is to read the error message and fix the issue.
Say, if it says that a particular table doesn't exist, you have to check spelling, typos, and letter case. Also you have to make sure that your PHP script connects to a correct database
Or, if it says there is an error in the SQL syntax, then you have to examine your SQL. And the problem spot is right before the query part cited in the error message.
If you don't understand the error message, try to google it. And when browsing the results, stick to answers that explain the error rather than bluntly give the solution. A solution may not work in your particular case, but the explanation will help you to understand the problem and make you able to fix the issue by yourself.
You have to also trust the error message. If it says that number of tokens doesn't match the number of bound variables then it is so. The same goes for the absent tables or columns. Given the choice, whether it's your own mistake or the error message is wrong, always stick to the former. Again it sounds condescending, but hundreds of questions on this very site prove this advise extremely useful.
A list of things you should never ever do in regard of error reporting
Never use an error suppression operator (#)! It makes a programmer unable read the error message and therefore unable to fix the error
Do not use die() or echo or any other function to print the error message on the screen unconditionally. PHP can report errors by itself and do it the right way depends on the environment - so just leave it for PHP.
Do not add a condition to test the query result manually (like if($result)). With error exceptions enabled such condition will just be useless.
Do not use the try..catch operator for echoing the error message. This operator should be used to perform some error handling, like a transaction rollback. But never use it just to report errors - as we learned above, PHP can already do it, the right way.
P.S.
Sometimes there is no error, but no results either. Then it means, there is no data in the database to match your criteria. In this case you have to admit this fact, even if you can swear the data and the criteria are all right. They are not. You have to check them again.
I've got an article that can help in this matter, How to debug database interactions. Although it is written for PDO, the principle is the same. Just follow those instructions step by step and either have your problem solved or have an answerable question for Stack Overflow.

AWS Lambda function working properly despite throwing timeout error and not resolving callback

I have a Lambda function that receives a message from SNS and uses a custom module that queries an external database and outputs calculations to the database. The module works fine: the Lambda has internet access via VPC and successfully connects to the database and outputs the desired data to the database, but I am still getting the error "Task timed out after 3.00 seconds." The module itself uses sequelize, async/await, and promises.
I increased the max timeout and the only difference was that the number of seconds in the error message increased to the timeout limit. I tried reserving concurrency and the error persists. Every part of my function works great other than the fact that the callback never resolves, producing a timeout error. I have tried running the function with and without the "context.callbackWaitsForEmptyEventLoop" statement, running it with the statement only makes the code return before any of the rating engine function is completed. Here is the rating engine code: https://github.com/elizajanus/rating-engine-module
Is it possible that the database connection is not closing within my custom module and preventing the code from fully completing the imported function? Or could it be something else? This issue may be connected: https://github.com/sequelize/sequelize/issues/8468
const {RatingEngine} = require('./rating-engine');
exports.handler = (event, context, callback) => {
const message = event.Records[0].Sns.Message;
RatingEngine(message, message.d_customer_id,
message.d_total_distance_travelled);
callback(null, 'move record created in database');
};
#Eliza Janus, you can test your code locally with https://www.npmjs.com/package/lambda-local, this will help you you to better identify the problem debugging the code.

How to get more specific errors, Ember Data 422 Error

I am attempting a post action using Ember-Data, and getting the following error which seems pretty common:
Error: The adapter rejected the commit because it was invalid
Problem is, seems like usually this returns more specific errors; I am only seeing the above message and a generic 422 error from the browser.
Does anyone know what I can do to access any specific error messages that might be thrown?
Potentially relevant info:
Using jsonapify on an express server to write to MongoDB
router.post('/',
jsonapify.create('info'),
logger.logErrors(), jsonapify.errorHandler()
);
I would expect the following code to log some sort of response but I am never able to see the message in this console.log:
info.save().then((response)=> {
console.log(`Server responded with ${response}`);
});
Sorry for the vagueness here, I'm sure there could be all sorts of problems with my models and whatnot, but I want to know what I can do to find the more specific errors if they exist.
Thanks much and plz lmk if I can update with more info.
.then() takes two arguments, like so: .then(success, failure) the first one being a function to be called on success, and the second to be called on failure. A 422 response is a failure, and your current code only has a success handler, so it will never be called. Basically, copy-paste your current success handler to be the second argument to your .then() call.
Also, generally in your browser you can open up the inspector and take a look at the request in the 'network' tab.
Your new debugging code could look something like this:
let success = (response) => {
console.log(`Server responded with ${response}`);
};
let failure = (response) => {
debugger;
};
info.save().then(success, failure);
Then you should be able to poke around the response object in your js console and see what's going wrong.

Node js mysql ending connection

i read a lot of topic on stack overflow and original docs of node-mysql but nowhere it is clearly described how to handle connections.
i create connection in the very beginning of my script with .createConnection(params)everything works fine i do my last operation with db and naturally im closing it by .end() method the problem starts here
when another user connects my server instead of creating new connection -which i wrote in the very beginning as i told- gives me an error Cannot enqueue Query after invoking quit
the point here i dont understand is i ended connection in previous users section end thi sis new user and script is called from the beginning
why an already ended connection cannot be re-connected is this a bug or am i doing something wrong
I found out the same connection cannot be used twice so i simply added a callback inside connection#end() and if theres no error i set my connection variable to null simply something like this
var connection =connection?connection:mysql.createConnection(dbParams);
connection.connect(
function(err){
if(err)console.log("cannot connect due to",err);
else console.log("connected");
})
//something happens here with db
connection.end(
function(err){
if(!err)connection=null;
else console.log(err)
});
And now everything works perfect

when this error come how to solve this error

I am developing an app in node.js socke.io redis mysql , so this error arrvied some time don't know when it arrived and how to find where this error come , how to solve this error .?
node.js:178
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: ETIMEDOUT, Connection timed out
at Socket._onConnect (net.js:600:18)
at IOWatcher.onWritable [as callback] (net.js:186:12)**strong text**
I believe I read somewhere on stackoverflow or someplace that socket.io is not yet completely comptatible with 0.5.0-pre. Could you try the latest official build v0.4.8 instead and report back?
That's correct :). I read it on stackoverflow.com and found the link to it also: node v0.5.0 pre Socket.IO crashes on connection (independent of transport)
This is caused by a socket error emitting an "error" event, but not finding any listeners for "error" events. In this case, node converts the event into an exception.
So the simple thing to check is make sure that you are listening for errors on all of your connections.
There is a tricky bug right now where some sockets emit errors before, or possibly after the user code can be listening for errors. I see this a lot when doing HTTPS. If you are hitting this uncatchable error situation, there's not much you can do about this besides changing node to not convert those socket errors into exceptions. If you can come up with a reliable way to reproduce this issue, it'll get fixed much more quickly.