1

Am coming from php background, now learning on how to move php mysql queries to nodejs. i have learnt how to work with nodejs insert, update and delete.

Now i have the code in php which returns queries in json format. what I want is how can I re-write this to nodejs json format.

below is the working php

if($request == 1){

    $result_arr = array();

    $query = "SELECT * FROM user where email='[email protected]' ";
    $result = mysqli_query($con,$query);

    while($row = mysqli_fetch_array($result)){
        $uid = $row['uid'];
        $name = $row['username'];


        // Checking user status
        $status_query = "SELECT count(*) as cntStatus FROM user_count_table WHERE uid='$uid'";
        $status_result = mysqli_query($con,$status_query);
        $status_row = mysqli_fetch_array($status_result);
        $count_status = $status_row['cntStatus'];

        $result_arr[] = array("id" => $uid, "username" => $name, "my_count" => $total_count);
    }

    echo json_encode($result_arr);
    exit;
}

below is my effort in trying to move the above php code to nodejs but cannot get it to work.

var connection = require('./config');
module.exports.getdata=function(req,res){
var email='[email protected]';

    connection.query('SELECT * FROM users WHERE email = ?',[email], function (error, results, fields) {
uid==results[0].uid;
name==results[0].username;
  connection.query('SELECT count(*) as cntStatus FROM user_count_table WHERE uid= ?',[uid], function (error, results, fields) {

total_count==results[0].cntStatus;
});
      if (error) {

 console.log('error');
        res.json({
            status:false,
            message:'there are some error with the query'

        })
      }else{


result_arr[] = array("id" => uid, "username" => name, "my_count" => total_count);

console.log('query okay');
          res.json({
//data:results,
data:result_arr       

        })
      }

}); 
}

1 Answer 1

2

There are several things which need to be refactored. You should already check for an error in the first callback. If no error is present, execute the second query and move the code where you assemble your response into the callback. Something like this:

var connection = require('./config');
module.exports.getdata = function (req, res) {
    var email = '[email protected]';

    connection.query('SELECT * FROM users WHERE email = ?', [email], function (error, results, fields) {
        if (error) {
            console.log('error');
            res.json({
                status : false,
                message : 'there are some error with the query'

            });
        } else {
            var uid == results[0].uid;
            var name == results[0].username;
            connection.query('SELECT count(*) as cntStatus FROM user_count_table WHERE uid= ?', [uid], function (error, results, fields) {

                if (error) {
                    console.log('error');
                    res.json({
                        status : false,
                        message : 'there are some error with the query'

                    });
                } else {

                    var total_count == results[0].cntStatus;
                    var result = {
                        "id" : uid,
                        "username" : name,
                        "my_count" : total_count
                    };

                    console.log('query okay');
                    res.json({
                        //data:results,
                        data : result

                    });
                }
            });
        }

    });
}

Also what you want is the response data to be an object, i.e. the JS-equivalent to an associative array in PHP.

One word of advice: Use promises/async await as it helps you to keep your code cleaner and prevent a callback hell.

Sign up to request clarification or add additional context in comments.

1 Comment

plus one for async/await. My code went from 'lost in stupid curlies' to readable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.