How to connect to MySQL through NODE.js and fetch our data?

Roll up your sleeves! We’re gonna get our hands dirty.

Although stableness is questionable in node.js, I’d like the async way node behaves unlike PHP. You can of course use PHP react to do the same thing, making PHP async but I love working with new stuff. And of course there are tools to make NODE.js more robust like forever module.

I assume you have installed node.js. If you want to work with mysql module you need to install it in node.js. Installing it is pretty straight forward. use node package manager(npm):

npm install mysql

Every module needs to be included in case you want to use it by require().

OK then what do you waiting for? include it in your project with some other modules that we’re gonna use:


var http = require('http');
var mysql = require('mysql');

We create a server with http module to send and receive our data with appropriate header (200, 403, etc).

You know better than me that mysql connection needs username, host, password,database. It makes no difference here. We just need to use createConnection() method to establish our connection:

As NODE.js rooted in java script, we use var to define our variable:


var connection = mysql.createConnection({
    host: 'localhost',
    user: "root",
    password: "",
    database: "bugxdb"
});

Here we are making a connection to bugxdb database and saving the resource inside connection variable.

Create an HTTP server as noted before to send and receive data (requests and responses). This server should listen on a specific port. My 8080 port is open so I use it.


http.createServer(function (req, res) {
    // we put all of our code here
}).listen(8080);

It’s easy right? I knew you would say YES.

Let’s suppose we have users table in bugxdb database. Now we put our query inside of a variable:


var uname='admin';

var query = 'SELECT email FROM users WHERE username=\'uname\' ';

A sample query to fetch admin email address.

Now all we need to do is to run our query with query() method and return the response.


connection.query(query, function (error, rows, fields) {

// when we're here and error is null it means voila! we ran query successfully!

});

Data will be populated inside of the rows input parameter. A pat on the back is only a few inches from a kick in the ass, as you have done all of this steps correctly you get the first one. Congratulations! ;-)

Send 200 OK header:

res.writeHead(200);
res.end(rows);

You may now ask how to test it? Fair enough don’t make me to do the second part on you (kick in the A**).

First of all let’s see our example as a whole:

var http = require('http');
var mysql = require('mysql');

var connection = mysql.createConnection({
host: 'localhost',
user: "root",
password: "",
database: "bugxdb"
});

http.createServer(function (req, res) {

var uname='admin';

var query = 'SELECT email FROM users WHERE username=\' uname\' ';

connection.query(query, function (error, rows, fields) {

// when we're here and error is null it means voila! we ran query successfully!
    res.writeHead(200);
    res.end(rows);
});
}).listen(8080);

Write this code in a file named bugxnode.js. And now run our nodejs file in shell as below:

nodejs bugxnode.js

Leave it there. Now point to your browser and go to http://localhost:8080 to see the results.

If you want to print a message in console write: console.log(‘your message’) I personally use it to debug my code in NODE.js code.

Feedspot.com – manage your feeds in one place

feedspot-homepageI’ve recently used Feedspot to manage my feeds. What I like most about this website is that you can discover new feeds inside it. It even suggests popular feeds that you can follow.

sidebar-feedspotAt the left side you can see my feeds from different websites and how many new feeds are waiting to be eaten/read.

Click on the browse categories to go to a whole new world in which you can get drawn inside of the websites ocean.

You can act like professionals by using the below keyboard shortcuts (press SHIFT+?):

feedspot-shortcuts

Right to the point tips, NO bullshit:

  • click the star at the right of the articles to see it inside Favorites folder.
  • Click add-new-site-feedspot and the enter http://bugx.ir/feed  or any other site’s feed then click add to follow site’s feed.
  • Use n/p or j/k for quick navigation

Feel free to tell us about your feed manager. Maybe yours is better! ;-)

Enable synaptics touchpad tapping in debian

I have an ancient laptop which I’ve bought in stone age. Don’t lOOk at me like that I’m a caveman too. Anyway as Ubuntu was heavy for my system even with XFCE, I installed Debian itself over network (special thanks to my friend Muhammad) with minimum installation packages. One of the major problems, at least for me, was that touch-pad tapping didn’t work. I could move my pointer through screen via touch-pad but I couldn’t tap on touch-pad to click or double click.

Grab the hammer inside of the cave and hit in the middle of your….oh wait my mistake just Create a directory inside /etc/X11 named xorg.conf.d in case you don’t have it and create a file called synaptics.conf .

Put the following code inside of the synaptics.conf:

Section "InputClass"
Identifier      "Touchpad"                      # required
MatchIsTouchpad "yes"                           # required
Driver          "synaptics"                     # required
Option          "MinSpeed"              "0.5"
Option          "MaxSpeed"              "1.0"
Option          "AccelFactor"           "0.075"
Option          "TapButton1"            "1"
Option          "TapButton2"            "2"     # multitouch
Option          "TapButton3"            "3"     # multitouch
Option          "VertTwoFingerScroll"   "1"     # multitouch
Option          "HorizTwoFingerScroll"  "1"     # multitouch
Option          "VertEdgeScroll"        "1"
Option          "CoastingSpeed"         "8"
Option          "CornerCoasting"        "1"
Option          "CircularScrolling"     "1"
Option          "CircScrollTrigger"     "7"
Option          "EdgeMotionUseAlways"   "1"
Option          "LBCornerButton"        "8"     # browser "back" btn
Option          "RBCornerButton"        "9"     # browser "forward" btn
EndSection

Put that hammer aside, job is done and we don’t need to do it the hard way! ;-)

Create a shell script in i3 wm for simpler reboot,lock,hibernate, etc

As you may know i3 is not a desktop environment, it’s is tiling window manager. It actually targets developers and advanced users. Shortcuts are king here. If you want to reboot your system from i3 or if you want to shutdown you need to type different commands which they don’t look similar to each other:

  1. To lock your system: lock
  2. to logout from i3:       i3-msg exit
  3. to hibernate:                lock && systemctl hibernate
  4. to poweroff system:  systemctl poweroff

You can clearly see that they all differ from each other. If you want to make it easy let’s create a script that would make our life easier.

Create a blank document in /usr/local/bin directory with your preferred text editor. I’ve used vim:

sudo vim /usr/local/bin/i3quit

Now paste the following code into your newly created shell file (i3quit):

 

#!/bin/sh
lock() {
    i3lock
}

case "$1" in
    lock)
        lock
        ;;
    logout)
        i3-msg exit
        ;;
    suspend)
        lock && systemctl suspend
        ;;
    hibernate)
        lock && systemctl hibernate
        ;;
    reboot)
        systemctl reboot
        ;;
    shutdown)
        systemctl poweroff
        ;;
    *)
        echo "Usage: $0 {lock|logout|suspend|hibernate|reboot|shutdown}"
        exit 2
esac

exit 0

In the above shell script we have a switch case that receives user input as $1. For instance, If user enters shutdown command then we run systemctl poweroff. After switch case inside the default case ( *) ) we echo our script usage to the console because user has misused our script and don’t know how to use it.

Now if you want to shutdown your system just type:

i3quit shutdown

Or if you want to logout:

i3quit logout

* You should make your shell script executable by sudo chmod +x i3quit.

Hot-keys make your life easier, especially when you have i3 window manager ;-)

Flash messages in Yii

It happens many times in project development life cycle that you want to show success or error messages. Well in Yii its pretty straight forward.

Yii stores flash messages in $_SESSION super global variable. We set a message with setFlash() and check if it exists with hasFlash() and finally get the flash message with getFlash().

Create your application with yiic. Inside your project create a controller named WebsiteController.php in protected/controllers/WebsiteController.php

Here we have 3 functions:

  1. actionIndex:     renders our default page.
  2. actionOk:          sets a success message and then redirect the user to the default page.
  3. actionBad:        sets an error message and redirect the user to index page.

Our WebsiteController will look like this:


class WebsiteController extends CController {
 function actionOk() {
     Yii::app()->user->setFlash('success', 'Record has been updated susseccfully!');
     $this->redirect('index');
 }
 function actionBad() {
     Yii::app()->user->setFlash('error', 'You don\'t have proper privileges to remove this record!');
     $this->redirect('index');
 }
 function actionIndex() {
     $this->render('index');
 }
}

The first parameter of setFlash() function is the name that we’re gonna get inside our view page. It can be anything.
The second parameter is our message content that we want to show to our user.

* Redirect function in Yii redirects our user to a specific page.

Now we should create our view page in protected/views/website/index.php which contains the below code:

<?php if(Yii::app()->user->hasFlash('success')):?>
     <div class="flash-notice">
        <?php echo Yii::app()->user->getFlash('success')?>
     </div>
<?php endif?>
<?php if(Yii::app()->user->hasFlash('error')):?>
     <div class="flash-error">
        <?php echo Yii::app()->user->getFlash('error')?>
     </div>
<?php endif?>

First we check if success or error is set then we echo our message in case it’s set. To access you site with error message got to your-path-to-yii/website/bad. The screen shot below shows the error message:

Yii-flash-messages

Now if you refresh the page session will be destroyed an error message will disappear.