How to create a PoolCluster in Node.js with MySQL

How to create a PoolCluster in Node.js with MySQL

To create a PoolCluster in Node.js with MySQL, you can follow these steps:

1. Install the mysql package in your Node.js project by running the following command in your terminal:

  npm install mysql
2. Require the mysql module in your Node.js code:
const mysql = require('mysql');
3. Create a new PoolCluster object:
const poolCluster = mysql.createPoolCluster();
4. Add one or more pools to the PoolCluster object:
const poolConfig1 = {
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'database1'
};

const poolConfig2 = {
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'database2'
};

poolCluster.add('MASTER', poolConfig1);
poolCluster.add('SLAVE', poolConfig2);

In this example, we're adding two pools to the PoolCluster object: one for the MASTER database and one for the SLAVE database.

5. Use the PoolCluster object to obtain connections from the appropriate pool:
poolCluster.getConnection('MASTER', (err, connection) => {
  if (err) throw err;

  connection.query('SELECT * FROM my_table', (error, results, fields) => {
    if (error) throw error;

    console.log(results);
    connection.release();
  });
});
In this example, we're obtaining a connection from the MASTER pool and executing a SELECT query on the my_table table.

6. Release the connection back to the pool when you're done with it:
connection.release();
That's it! You now have a working PoolCluster object that you can use to manage connections to multiple MySQL databases in your Node.js application.
How to get the checked value of the radio button in javascript

How to get the checked value of the radio button in javascript

Hi, In This tutorial you will learn about "How to get the checked value of the radio button in javascript". If working on the javascript to get the values of the radio buttons it some times gets the not checked value or same value can be retrieved. Because when you write the radio buttons code any radio button is checked default
<input type="radio" id="lang" name="language" value="PHP" checked> PHP  
In javascript, we will retrieve this value as
var  language = document.getElementById('lang').value;
alert(language);
it will work perfectly when only one radio button. In another case, if you have the multiple radio buttons you need to check the every radio button is checked or not before getting the value from the radio button.

i.e, For Example, I showed the above example only one language but here I am taking the multiple languages.
 <input type="radio" id="lang1" name="language" value="PHP" checked> PHP  
 <input type="radio" id="lang2" name="language" value="Jquery"> Jquery  
 <input type="radio" id="lang3" name="language" value="MySql"> MySql  
 <input type="radio" id="lang4" name="language" value="Html"> Html  
 <input type="radio" id="lang5" name="language" value="CSS"> CSS  
 <input type="radio" id="lang6" name="language" value="JavaScript"> JavaScript  
In the above example name must be the same to all the radio buttons so that only one language can be selected. it is the default nature of the radio button. But you need to change the id of the name like the above code it is necessary to check the each and every radio button is checked or not before getting the checked value.
var language = "";  
 if (document.getElementById('lang1').checked) {  
  language = document.getElementById('lang1').value;  
 }else if (document.getElementById('lang2').checked) {  
  language = document.getElementById('lang2').value;  
 }else if (document.getElementById('lang3').checked) {  
  language = document.getElementById('lang3').value;  
 }else if (document.getElementById('lang4').checked) {  
  language = document.getElementById('lang4').value;  
 }else if (document.getElementById('lang5').checked) {  
  language = document.getElementById('lang5').value;  
 }else if (document.getElementById('lang6').checked) {  
  language = document.getElementById('lang6').value;  
 }  
 alert(language);  
* If you like this post please don't forget to subscribe TechiesBadi - programming blog for more useful stuff
How to disable the browser back button navigation using javascript

How to disable the browser back button navigation using javascript

Hi, Today you will learn about "How to disable the browser back button navigation using javascript", In general, we don't use this type of requirement in the project.But is very useful in so many situations.

For example, we are doing in the online cart i.e an e-commerce platform so here after the placing the order and once the user checks out the order in his cart and payment completed it will redirect and shown the order success page after that user doesn't go back to the previous pages. So here we want to block the browser back button navigation.

So here in this situation we will use this code. if you searched on the internet you will find the code i.e
<script type="text/javascript">  
     window.history.forward();  
     function noBack()  
     {  
       window.history.forward();  
     }  
 </script>  
 <body onLoad="noBack();" onpageshow="if (event.persisted) noBack();" onUnload="">   
This code is not working properly. so I have found the solution to this problem. Just add the below script code on the file where the user doesn't go back from that file.
<script type="text/javascript">  
 (function (global) {   
   if(typeof (global) === "undefined") {  
     throw new Error("window is undefined");  
   }  
   var _hash = "!";  
   var noBackPlease = function () {  
     global.location.href += "#";  
     // making sure we have the fruit available for juice (^__^)  
     global.setTimeout(function () {  
       global.location.href += "!";  
     }, 50);  
   };  
   global.onhashchange = function () {  
     if (global.location.hash !== _hash) {  
       global.location.hash = _hash;  
     }  
   };  
   global.onload = function () {        
     noBackPlease();  
     // disables backspace on page except on input fields and textarea..  
     document.body.onkeydown = function (e) {  
       var elm = e.target.nodeName.toLowerCase();  
       if (e.which === 8 && (elm !== 'input' && elm !== 'textarea')) {  
         e.preventDefault();  
       }  
       // stopping event bubbling up the DOM tree..  
       e.stopPropagation();  
     };       
   }  
 })(window);  
 </script>  
Here you can check the demo.
Demo
* If you like this post please don't forget to subscribe TechiesBadi - programming blog for more useful stuff
How to read the .docx files in PHP

How to read the .docx files in PHP

Hi, In This tutorial you will learn about "How to read the .docx files in PHP". Generally .docx files will be opened in the MS-OFFICE, But we are able to open the .docx file in PHP we have to convert the .docx file into text then we can easily display the content in the web browser.

<?php  
 function read_file_docx($filename){  
      $striped_content = '';  
      $content = '';  
      if(!$filename || !file_exists($filename)) return false;  
      $zip = zip_open($filename);  
      if (!$zip || is_numeric($zip)) return false;  
      while ($zip_entry = zip_read($zip)) {  
      if (zip_entry_open($zip, $zip_entry) == FALSE) continue;  
      if (zip_entry_name($zip_entry) != "word/document.xml") continue;  
      $content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));  
      zip_entry_close($zip_entry);  
      }// end while  
      zip_close($zip);  
      $content = str_replace('</w:r></w:p></w:tc><w:tc>', " ", $content);  
      $content = str_replace('</w:r></w:p>', "\r\n", $content);  
      $striped_content = strip_tags($content);  
      return $striped_content;  
 }  
 $filename = "sample.docx";// or /var/www/html/file.docx  
 $content = read_file_docx($filename);  
 if($content !== false) {  
      echo nl2br($content);  
 }  
  else {  
      echo 'Couldn\'t the file. Please check that file.';  
           }  
 ?>  

* If you like this post please don't forget to subscribe TechiesBadi - programming blog for more useful stuff
How to save an HTML5 Canvas as Image on a server using PHP

How to save an HTML5 Canvas as Image on a server using PHP

Hi, In this tutorial, I am going to explain, How to save an HTML5 Canvas as Image on a server using PHP. Before going to this topic please refer "How to convert the HTML content into an image using jquery" in my previous post then you will get an idea how to generate the div content as an image.

Step 1: First Convert canvas image to URL format (base64)
var dataURL = canvas.toDataURL();
Step 2: After Send it to your server via Ajax
$.ajax({
  type: "POST",
  url: "script.php",
  data: { 
     imgBase64: dataURL
  }
}).done(function(o) {
  console.log('saved'); 
});
Step 3: Now Save base64 on your server as an image using php code
<?php  
      // requires php5  
      define('UPLOAD_DIR', 'images/');  
      $img = $_POST['imgBase64'];  
      $img = str_replace('data:image/png;base64,', '', $img);  
      $img = str_replace(' ', '+', $img);  
      $data = base64_decode($img);  
      $file = UPLOAD_DIR . uniqid() . '.png';  
      $success = file_put_contents($file, $data);  
      print $success ? $file : 'Unable to save the file.';  
 ?>  
Here you can download the Full Source code and check the demo.

Download Demo
* If you like this post please don't forget to subscribe TechiesBadi - programming blog for more useful stuff
How to Refresh a page after specific time automatically in PHP

How to Refresh a page after specific time automatically in PHP

Hi, In This tutorial you will know about How to Refresh a page after specific time automatically in PHP. Generally, we did this type of implementation in the javascript or jquery but sometimes javascript is disabled in the user's side (i.e users disabled the javascript in their browsers).

At this situation, we need to implement that code in PHP
it is very simple first we need to fix the specific time for the refresh the website.
In general, the header is used to redirect the web page in PHP by using the location. But here we will use the header in the Refresh tag to set the time and web page URL to refresh the web page.

 //getting the current web page url
 $page = $_SERVER['PHP_SELF'];
 //set the time in seconds
 $sec = "10";
 header("Refresh: $sec; url=$page");
* If you like this post please don't forget to subscribe TechiesBadi - programming blog for more useful stuff
How to store and retrieve array in MySQL and PHP

How to store and retrieve array in MySQL and PHP

This is the most important technique for all Php developers because of Mysql can't store the array values directly.
So we need to convert the PHP Array to string by using the serialize().

This mechanism is very useful in the e-commerce cart functionality. For example, we can store the customer purchase items list and price can be stored in the associative array and convert into string and store in the MySQL.
This way we can reduce the logic of the code get the accurate result also.

MySql Code
CREATE TABLE `students` (
  `id` int(11) NOT NULL,
  `language` varchar(50) NOT NULL,
  `student_names` mediumtext NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for table `students`
--
ALTER TABLE `students`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for table `students`
--
ALTER TABLE `students`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
You need to connect the database create the dbconfig.php file
 <?php  
 $servername = "localhost";  
 $username = "root";  
 $password = "";  
 $dbname = "techiesbadi";  
 // Create connection  
 $con = new mysqli($servername,$username, $password, $dbname);  
 // Check connection  
 if ($con->connect_error) {  
 die("Connection failed: " . $con->connect_error);  
 }  
 ?> 
Now Store the PHP Array in MySql create the store-array.php file
 <?php  
 include "dbconfig.php";  
 $students = array("ramu", "ravi", "gopal", "krishna");  
 //Converting array to String  
 $student_names=mysqli_real_escape_string($con, serialize($students));  
 $sql = "INSERT INTO `students` (`id`, `language`, `student_names`) VALUES (NULL, 'php', '$student_names')";  
 $result = $con->query($sql);  
 if($result === TRUE){  
      echo "Record inserted successfully";  
 }  
 ?>
Now retrieve the PHP Array from MySQL create the retrieve-array.php file
<?php  
 include "dbconfig.php";  
 $getStudnets = $con->query("SELECT * FROM `students` LIMIT 1");   
 $studentsData = $getStudnets->fetch_object();  
 $language = $studentsData->language;  
 //Converting string to array  
 $students = unserialize($studentsData->student_names);  
 //printing students array  
 print_r($students);  
 echo "<br />";  
 foreach ($students as $student) {  
      echo $student." learning ".$language." language.<br/>";  
 }  
 ?>
Here you can download the Full Source code and check the demo.

Download Demo
* If you like this post please don't forget to subscribe TechiesBadi - programming blog for more useful stuff

How to Generate QR Code using Google Chart API in PHP

Hi, In this tutorial you will learn How to Generate QR Code using Google Chart API in PHP. Before going to the topic you need to know about what is QR Code?
QR Code is a machine-readable code, It consisting of an array of black and white squares. It is typically used for storing the information like general text, contact information, URL, image and SMS this information is reading by the smartphone cameras and QRcode Scanner Devices.

If you want to generate the QRcode in PHP you shall need to load the lots of libraries to your application.But we use this  Google chart API to generate the QRcode. Here there is no need to load the libraries to your application just we use the Google Chart API and CURL.

The Script allows you to create the dynamic QRcodes for the content like  TEXT, URL, EMAIL, CONTACT, SMS and other details.
You can save the generated QR code as a PNG file.

qrcode.php
<?php  
 class QrCode{  
   // Google Chart API URL  
   private $apiUrl = 'http://chart.apis.google.com/chart';  
   private $data;  
   // It generates URL type of Qr code  
   public function URL($url = null){  
     $this->data = preg_match("#^https?\:\/\/#", $url) ? $url : "http://{$url}";  
   }  
    // It generate the Text type of Qr code  
   public function TEXT($text){  
     $this->data = $text;  
   }  
   // It generates the Email type of Qr code  
      public function EMAIL($email = null, $subject = null, $message = null) {  
           $this->data = "MATMSG:TO:{$email};SUB:{$subject};BODY:{$message};;";  
      }  
   //It generates the Phone numner type of Qr Code  
   public function PHONE($phone){  
     $this->data = "TEL:{$phone}";  
   }  
   //It generates the Sms type of Qr code  
      public function SMS($phone = null, $msg = null) {  
           $this->data = "SMSTO:{$phone}:{$msg}";  
      }  
   //It generates the VCARD type of Qr code  
      public function CONTACT($name = null, $address = null, $phone = null, $email = null) {  
           $this->data = "MECARD:N:{$name};ADR:{$address};TEL:{$phone};EMAIL:{$email};;";  
      }  
   // It Generates the Image type of Qr Code  
      public function CONTENT($type = null, $size = null, $content = null) {  
           $this->data = "CNTS:TYPE:{$type};LNG:{$size};BODY:{$content};;";  
      }  
   // Saving the Qr code image   
      public function QRCODE($size = 400, $filename = null) {  
           $ch = curl_init();  
           curl_setopt($ch, CURLOPT_URL, $this->apiUrl);  
           curl_setopt($ch, CURLOPT_POST, true);  
           curl_setopt($ch, CURLOPT_POSTFIELDS, "chs={$size}x{$size}&cht=qr&chl=" . urlencode($this->data));  
           curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
           curl_setopt($ch, CURLOPT_HEADER, false);  
           curl_setopt($ch, CURLOPT_TIMEOUT, 30);  
           $img = curl_exec($ch);  
           curl_close($ch);  
           if($img) {  
                if($filename) {  
                     if(!preg_match("#\.png$#i", $filename)) {  
                          $filename .= ".png";  
                     }  
                     return file_put_contents($filename, $img);  
                } else {  
                     header("Content-type: image/png");  
                     print $img;  
                     return true;  
                }  
           }  
           return false;  
      }  
 }  
 ?>
To create the QR code you need to include the qrcode.php file in your index.php file
<?php  
 include "qrcode.php";   
 // Create QRcode object   
 $qc = new QRCODE();   
 // create text QR code   
 $qc->TEXT("TechiesBadi");     
 // render QR code  
 $qc->QRCODE(400,"qrcode.png");  
 ?>  
Like this you can generate the remainig Qrcodes.
// URL QR code 
$qc->URL('www.techiesbadi.in');

// EMAIL QR code 
$qc->EMAIL('info@techiesbadi.in', 'SUBJECT', 'MESSAGE');

// PHONE QR code 
$qc->PHONE('PHONENUMBER');

// SMS QR code 
$qc->SMS('PHONENUMBER', 'MESSAGE');

// CONTACT QR code 
$qc->CONTACT('NAME', 'ADDRESS', 'PHONE', 'EMAIL');
Here you can download the Full Source code and check the demo.

Download Demo
* If you like this post please don't forget to subscribe TechiesBadi - programming blog for more useful stuff