Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Saturday, February 11

CURL Send file PHP – Send file using CURL with PHP

CURL Send file PHP – Send file using CURL with PHP

In this post we will show you CURL Send file PHP :: How to Send a file using CURL with PHP via POST method, hear we was operating on a project wherever we wanted to send a file mistreatment CURL to a 3rd party web server and that we tried several post out there on web however they didn’t work on behalf of me. But whereas googling, we found an simple and easy thanks to send files on to its destination.
Here is the code for CURL Send file PHP ::

<form method="post" action="#" name="curl_form">
    <label>Select Yous File For curl:</label>
    <input type="file" name="curl_image_upload" />
    <input type="submit" name="submit" value="Send" />
</form>

And my PHP code that will be CURL Send file.

<?php
    $image_upload_val = array(
        'curl_image_upload'=> new CurlFile($_FILES['curl_image_upload']['tmp_name'], $_FILES['curl_image_upload']['type'], $_FILES['curl_image_upload']['name']),
    );
    // curl connection
    $ch = curl_init();
    // set curl url connection
    $curl_url = "http://www.your-domin-name.com/api/curl_image_upload";
    // pass curl url
    curl_setopt($ch, CURLOPT_URL,$curl_url);
    curl_setopt($ch, CURLOPT_POST, 1);
    // image upload Post Fields
    curl_setopt($ch, CURLOPT_POSTFIELDS,$image_upload_val);
    // set CURL ETURN TRANSFER type
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $server_result = curl_exec($ch);
    curl_close($ch);
    echo $server_result;
    exit;
?>

we hope this small guide will help you for CURL Send file PHP. Please share your comments in the comment box below.

Saturday, January 14

how to connect database with mysql, MySQLi , pdo – php

how to connect database with mysql, MySQLi , pdo in php

Mysql database connection

$database_host = 'localhost'; // database host name
// if using port then add port $database_host = 'localhost:3036'; 
$database_user = 'database_user'; // database user name
$database_pass = 'database_password'; // database user password

// connect with database
$database_conn = mysql_connect($database_host, $database_user, $database_pass);

// check database connection
if(! $database_conn )
{
    // error in database connection
    die('Could not connect to database : ' . mysql_error());
}
// connected to database
echo 'Connected successfully with database';

// close connection with Mysql database
mysql_close($database_conn); 


MySQLi Object-Oriented database connection

$database_host = 'localhost'; // database host name
// if using port then add port $database_host = 'localhost:3036'; 
$database_user = 'database_user'; // database user name
$database_pass = 'database_password'; // database user password

// connect with database
$database_conn = new mysqli($database_host, $database_user, $database_pass);

// check database connection
if ($database_conn->connect_error)
{  
    // error in database connection
    die("Could not connect to database : " . $database_conn->connect_error);
}

// connected to database
echo 'Connected successfully with database';

// close connection with MySQLi database
$database_conn->close();

MySQLi Procedural database connection

$database_host = 'localhost'; // database host name
// if using port then add port $database_host = 'localhost:3036'; 
$database_user = 'database_user'; // database user name
$database_pass = 'database_password'; // database user password

// connect with database
$database_conn = mysqli_connect($database_host, $database_user, $database_pass);

// check database connection
if (!$database_conn)
{
    // error in database connection
    die("Could not connect to database : " . mysqli_connect_error());
}

// connected to database
echo 'Connected successfully with database';

// close connection with MySQLi Procedural
mysqli_close($database_conn);

PDO database connection

$database_host = 'localhost'; // database host name   
$database_user = 'database_user'; // database user name
$database_pass = 'database_password'; // database user password
$database_name = 'your_database_name'; // database name

try
{
    $database_conn = new PDO("mysql:host=$database_host;dbname=$database_name", $database_user, $database_pass);
    // if using port then use port id in PDO 
    //$database_conn = new PDO('mysql:host=$database_host;port=5432;dbname=$database_name', $database_user, $database_pass);
    
    // exception for PDO connection error
    $database_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // connected to database
    echo 'Connected successfully with database';
}
catch(PDOException $exception)
{
    // error in database connection
    echo "Could not connect to database : " . $exception->getMessage(); // exception
}

// close connection with PDO
$database_conn = null;


PHP – send email with attachment file

how to send email with attachment file in PHP

In this post we will show you how to send email with attachment in php. by using this following code is used for send email with attachment in php. following code will sending pdf file in email.

$file_name = "example.pdf"; // attachment file name
$path = "folder_name"; // path of attachment file
$user_name = "user name"; // user name
$mail_to = "onlinecode@email.com"; // to eamil
$email_subject = "Notification of attachment for user"; // subject of eamil
$body_text = "Hello ".$user_name.",\nThis demo message with file attachment. You will be notified when their review has been completed.\n Regard \n onlinecode Team";

$attachment_file = $path . "/" . $file_name; // path of file
$attachment_file_size = filesize($attachment_file);
$email_handle = fopen($attachment_file, "r");
$content = fread($email_handle, $attachment_file_size);
fclose($email_handle);// file close of email handle
$content = chunk_split(base64_encode($content));
$time_separator = md5(time());// a random hash will be necessary to send mixed content

// carriage return type (we use a PHP end of line constant)
$email_eol = PHP_EOL;
$body_message = $body_text;
// main header (multipart mandatory)
$email_headers = "From: onlinecode.org Team &lt;onlinecode@email.co&gt;" . $email_eol;
// sender eamil detail
$email_headers .= "MIME-Version: 1.0" . $email_eol;//MIME-Version
$email_headers .= "Content-Type: multipart/mixed; boundary=\"" . $time_separator . "\"" . $email_eol;//Content-Type
$email_headers .= "Content-Transfer-Encoding: 7bit" . $email_eol;//Content-Transfer-Encoding
$email_headers .= "This is a MIME encoded message." . $email_eol;

// eamil message
$email_headers .= "--" . $time_separator . $email_eol;
$email_headers .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $email_eol;
$email_headers .= "Content-Transfer-Encoding: 8bit" . $email_eol;
$email_headers .= $body_message . $email_eol;

// attachment
$email_headers .= "--" . $time_separator . $email_eol;
$email_headers .= "Content-Type: application/octet-stream; name=\"" . $file_name . "\"" . $email_eol;
$email_headers .= "Content-Transfer-Encoding: base64" . $email_eol;
$email_headers .= "Content-Disposition: attachment" . $email_eol;
$email_headers .= $content . $email_eol;
$email_headers .= "--" . $time_separator . "--";
mail($mail_to, $email_subject, ", $email_headers); //SEND Mail TO USER

 

Friday, January 13

php json encode and decode example

<?php
echo "<br><h1>JSON Encode_decode with php</h1></br>";
echo"JSON_DECODE<br/>--------------------------------------------";
echo"<br/>";
$json = '{"a":1,"b":2,"c":3}';//Example 1
$j=json_decode($json);

echo "Value a= ". $j->{'a'};
echo "Value b= ". $j->{'b'};
echo "Value c= ". $j->{'c'};

echo"<br/>--------------------------------------------";
echo"<br/>";
echo"JSON_ENCODE<br/>--------------------------------------------";
echo"<br/>";

$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);//Example 2
echo json_encode($arr);
echo"<br/>";
// Output {"a":1,"b":2,"c":3,"d":4,"e":5}


$arr = array ( 1, 2, 3, 4, 5 ); //Example 3
echo json_encode($arr);
echo"<br/>";
// Output [1,2,3,4,5]


$arr['x'] = 10;  //Example 4
echo json_encode($arr);
echo"<br/>";
// Output {"0":1,"1":2,"2":3,"3":4,"4":5,"x":10}


echo json_encode(54321); //Example 5
echo"<br/>";
// Output 54321
echo"<br/>--------------------------------------------";

//Example 1

echo "<br/>Example #1 : The following example shows how to convert an ARRAY INTO JSON WITH PHP
<br/><br/><br/>";

$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
echo "<br/>";

//Example 2


echo "<br/>Example #2 : The following example shows HOW THE PHP OBJECTS CAN BE CONVERTED INTO JSON
<br/><br/><br/>";

class Emp {
public $name = "";
public $hobbies = "";

}
$e = new Emp();
$e->name = "sachin";
$e->hobbies = "sports";

echo json_encode($e);

//Example 3

echo "<br/>Example #3 : The following example shows HOW PHP CAN BE USED TO DECODE JSON OBJECTS
<br/><br/><br/>";

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
echo "<pre>".var_dump(json_decode($json))."</pre>";
echo "<pre>".var_dump(json_decode($json, true))."</pre>";
echo "<br/>";

//Example 4

echo "<br/>Example #3 : The following example shows HOW PHP CAN BE USED TO DECODE JSON OBJECTS
<br/><br/><br/>";

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
echo "<pre>".var_dump(json_decode($json))."</pre>";
echo "<pre>".var_dump(json_decode($json, true))."</pre>";
echo "<br/>";


?>

get longitude and latitude from an address with PHP and Google Maps API :Example

<?php
$url = "http://maps.google.com/maps/api/geocode/json?address=india+gujrat+rajkot&sensor=false&region=India";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);

$response = json_decode($response);
echo "<pre>";
print_r($response);
echo "<pre>";

echo "Latitude : ".$lat = $response->results[0]->geometry->location->lat;
echo "<br/>";
echo "Longitude :".$long = $response->results[0]->geometry->location->lng; 
?>

Example 2:

<?php
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://completion.amazon.com/search/complete?search-alias=aps&client=amazon-search-ui&mkt=1&q=google");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
echo curl_getinfo($curl, CURLINFO_HTTP_CODE); // code here
curl_close($curl);

die();
echo "<pre>";
print_r(json_decode($result));//return amazone autocomplete suggestion
echo "</pre>";
?>

Get City Country By IP Address in PHP

index.php

<?php
$ip_addressget=$_SERVER['REMOTE_ADDR'];

/*Get user ip address details with geoplugin.net*/
$geopluginURL='http://www.geoplugin.net/php.gp?ip='.$ip_addressget;

$addrDetailsArr = unserialize(file_get_contents($geopluginURL));

/*Get City name by return array*/
$city = $addrDetailsArr['geoplugin_city'];

/*Get Country name by return array*/
$country = $addrDetailsArr['geoplugin_countryName'];

/*Comment out these line to see all the posible details*/
/*echo '<pre>';
print_r($addrDetailsArr);
die();*/

if(!$city){
   $city='Not Define';
}if(!$country){
   $country='Not Define';
}
echo '<strong>IP Address is</strong>:- '.$ip_address.'<br/>';
echo '<strong>City is </strong>:- '.$city.'<br/>';
echo '<strong>Country is </strong>:- '.$country.'<br/>';
?>

PHP String Functions with Example

<?php
//Get The Length of a String :Example
echo strlen("Welcome WEB!"); // outputs 10

//Count The Number of Words in a String :Example
echo str_word_count("Welcome WEB!"); // outputs 2

//Reverse a String :Example
echo strrev("Hello world!1"); // outputs 1!dlrow olleH

//Search For a Specific Text Within a String :Example
 echo strpos("Hello world!", "world"); // outputs 6

//Replace Text Within a String :Example
echo str_replace("world", "King", "Hello world!"); // outputs Hello King!


//PHP Strlen() Function :Example

$name="king";
if ( strlen( $name ) != 5 ) 
{
    echo "Correct input.";
}
else
{
    echo "incorrect input";
}

//PHP chr() FUNCTION :Example
echo chr(35); //#

//PHP strcmp()FUNCTION :Example
<?php echo strcmp("Hello world!","Hello world!"); ?> //Returns 0

//PHP explode()FUNCTION :Example

 $str = "Hello world. It's a beautiful day.";
 print_r (explode(" ",$str));
/* Output :
Array
 (
 [0] => Hello
 [1] => world.
 [2] => It's
 [3] => a
 [4] => beautiful
 [5] => day.
 )
*/

//PHP implode()FUNCTION :Example

$arr = array('Hello','World!','Beautiful','Day!');
 echo implode(" ",$arr);
/*
Output:
Hello World! Beautiful Day!
*/

//PHP str_replace()FUNCTION :Example

 $phrase  = "You should eat fruits, vegetables, and fiber every day.";
 $healthy = array("fruits", "vegetables", "fiber");
 $yummy   = array("pizza", "beer", "ice cream");
 $newphrase = str_replace($healthy, $yummy, $phrase);

/*
Output :
You should eat pizza, beer, and ice cream every day
*/

//PHP substr()FUNCTION :Example

 echo substr("Hello world",6);  //Returns world
 echo substr("Hello world",6,4); // Returns worl
 echo substr("Hello world", -1); // Returns  d
 echo substr("Hello world", -3, -1); // Returns rl

?>

PHP Connect to My SQL Database

<?php
$ng_username = "your_user_name";//localhost
$ng_password = "your_user_password";//password
$ng_hostname = "localhost/servername"; //127.0.0.1

//The connection to the database using PHP
$dbhandle = mysql_connect($ng_hostname, $ng_username, $ng_password)
  //or die(mysql_error());//Show Error generated.
  or die("in database connection details : Does not connect Mysql Databased ");
echo "database connection details : Your Database Connected to MySQL succesfully<br>";
?>


//Other way to select a database to work with


<?php
$selected = mysql_select_db("DatabaseName",$dbhandle_varname)or die("details of connect database - can not connect your database");
?>

Second way to external php to MYSQL connect databased- config.php
----------

<?php
$username_ng = "root";//localhost
$password_ng = "ng4free";//password
$hostname_ng = "localhost or ip"; //127.0.0.1

//connection to the database
$dbhandle = mysql_connect($hostname_ng, $username_ng, $password_ng)
  or die("Disconnect your databased in MYSQL/ Unable to connect to MySQL : details");
echo "You are Connected to MySQL Databased<br>";

$selected_databased = mysql_select_db("users",$dbhandle)or die("Databased Details : does not/Could not select users");

?>

Full Example : How to connect to MySQL database using PHP

<?php
$user_username = "Default (root)Your username or root";
$user_password = "Host (Password)genrated password";
$user_hostname = "localhost / server host";

//The above us to connection to the database
$dbhandle = mysql_connect($user_hostname, $user_username, $user_password)
 or die("Error : Unable to connect to MySQL");
echo "PHP to connect MySQL Databased success. <br>";

//The Script is select a database to work with
$selected = mysql_select_db("test",$dbhandle)
  or die("Could not select test");

//IT's is query execute the SQL query(handle) and return records
$result_data = mysql_query("SELECT your_id, modelname,year FROM cars_company");

//Loop through fetch tha data from the database Using PHP Script
while ($row = mysql_fetch_array($result_data)) {
   echo "ID:".$row{'your_id'}." Name:".$row{'modelname'}."Year: ". //Print display the results
   $row{'year'}."<br>";
}
//Dtabased close the connection
mysql_close($dbhandle);//connection close
?>

Now Go To Localhost/phpmyadmin and to create 'cars_company' database on your MySQL server you should run the following script:

CREATE DATABASE `users`;
USE `cars_company`;
CREATE TABLE `cars_company` (
   `your_id` int UNIQUE NOT NULL,
   `modelname` varchar(40),
   `year` varchar(50),
   PRIMARY KEY(your_id)
);

INSERT INTO cars_company VALUES(1,'ngcomapny','2000');
INSERT INTO cars_company VALUES(2,'ng4free','2004');
INSERT INTO cars_company VALUES(3,'ngdemo','2001');

Wednesday, January 4

How to convert an array to object in PHP?

How to convert an array to object in PHP?
This post will show you how to convert convert an array to object with different conditions of array in PHP.
Convert array to object using json.


The Best, quick, dirty, very effective and easy way (also my personal recommendations) to convert array to objects using json_encode and json_decode, it will turn the entire array (also including sub elements of array) into an object.

// Convert array into an object
$object = json_decode(json_encode($array));

var_dump ($object); // print object value with var_dump   


Convert associative array in to object

$array = Array ( 'keys' => "status value" );
// convert array in to object
$object = (object) $array;

var_dump ($object); // print object value with var_dump

var_dump($object->keys); // echo object value using key

Convert mulch-dimensional array( with same associative array) to object with simple way


$array = array (
    "0" => Array( "status_key" => "test value of keys 0" ),
    "1" => Array( "status_key" => "test value of keys 1" ),
    "2" => Array( "status_key" => "test value of keys 2" )
);

simple way convert array in to object

// convert array in to object
$object = (object) $array;
var_dump ($object); // print object value with var_dump

This is another way to convert array to object with foreach loop

$object = new stdClass();

foreach ($array as $keys => $value ) {
    $object->{$keys} = $value;
}
var_dump ($object); // print object value with var_dump

In this mulch-dimensional array we will convert into an object.

$array = array (
    "test array",
    array( "keys test 1 value" ,"keys test 2 value" ,"keys test 3 value" ),
    array( "keys test 1 value" ,"keys test 2 value" ,"keys test 3 value" ),
    array( "keys test 1 value" ,"keys test 2 value" ,"keys test 3 value" ),
    array( "keys test 1 value" ,"keys test 2 value" ,"keys test 3 value" ),
);

$object = new ArrayObject($array);
var_dump ($object); // print object value with var_dump

foreach ($object as $keys => $val){
    if (is_array( $val )) {
        foreach($val as $sub_key => $sub_val) {
           echo $sub_key . ' => ' . $sub_val."<br>";
        }
    }
    else
    {
           echo $val."<br>";
    }
}

Convert array to object using function (with same associative array)

function arrat_to_object($array) {
    $objects = new stdClass();
    foreach ($array as $keys => $value) {
        if (is_array($value)) {
            $value = arrat_to_object($value);
        }
        $objects->$keys = $value;
    }
    return $objects;
}


$object = arrat_to_object($array); // pass array
var_dump ($object); // print object value with var_dump

Convert Manually array in to an object

$object = object; // assign array
foreach ($array as $keys => $values) {
    $object->{$keys} = $values;
}
var_dump ($object); // print object value with var_dump 


 

MySQL Select Query in php to select the records

MySQL Select Query is used to select the records from MySQL database tables in php

how to use MySQL Select Query is used to select the records from MySQL database tables using php.

PHP Select Data From MySQL(MySQL Select Query)

  PHP Select Data From MySQL

database name :: onlinecode_db
table name :: user_table
+----+------------+-----------+-----------------------------+
| id | first_name | last_name | user_email                  | // column name
+-----------+------------+-----------+----------------------+
| 1  | Peter      | Kong      | peterKong@mail.com          |
| 2  | John       | smith     | johnsmith@mail.com          |
| 3  | Shuvo      | Kent      | Shuvokent@mail.com          |
| 4  | John       | Habib     | johnHabib@mail.com          |
| 5  | Anthony    | Potter    | Anthonypott@mail.com        |
+-----------+------------+-----------+----------------------+

$database_host = 'localhost'; // database host name
 // if using port then add port $database_host = 'localhost:3036'; 
 $database_user = 'database_user'; // database user name
 $database_pass = 'database_password'; // database user password
 $database_name = 'onlinecode_db';  // database name
 
// connect with database
 $database_conn = mysql_connect($database_host, $database_user, $database_pass);
 
 // check database connection
 if(! $database_conn )
 {
     // error in database connection
     die('Could not connect to database : ' . mysql_error());
 }
 $sql_select_query = 'SELECT id,first_name,last_name,user_email FROM user_table';

 mysql_select_db($database_name);
 $sql_result = mysql_query( $sql_select_query, $database_conn );
 if(! $sql_result )
 {
     // error in sql query or Fetch data
     die('Could not get data: ' . mysql_error());
 }
 while($result = mysql_fetch_array($sql_result, MYSQL_ASSOC))
 {
     echo "User ID :{$result['id']}".
          "First Name : {$result['first_name']}".
          "Last Name : {$result['last_name']}".
          "Email Address : {$result['user_email']}";
 }
 echo "Get data successfully";
 
 // close connection with Mysql database
 mysql_close($database_conn);   


PHP Select Data From MySQLi Object-Oriented(MySQL Select Query)

 $database_host = 'localhost'; // database host name
// if using port then add port $database_host = 'localhost:3036'; 
$database_user = 'database_user'; // database user name
$database_pass = 'database_password'; // database user password
$database_name = 'onlinecode_db';  // database name

// connect with database
$database_conn = new mysqli($database_host, $database_user, $database_pass, $database_name);

// check database connection
if ($database_conn-&gt;connect_error)
{  
    // error in database connection
    die("Could not connect to database : " . $database_conn-&gt;connect_error);
}

$sql_select_query = 'SELECT id,first_name,last_name,user_email FROM user_table';
$sql_result =  $database_conn-&gt;query($sql_select_query);

if ($sql_result-&gt;num_rows &gt; 0) {
    // output data of each row
    while($result = $sql_result-&gt;fetch_assoc()) {
        echo "User ID :{$result['id']}".
         "First Name : {$result['first_name']}".
         "Last Name : {$result['last_name']}".
         "Email Address : {$result['user_email']}";        
    }
} else {
    echo "No data found";
}

// close connection with MySQLi database
$database_conn-&gt;close();

PHP Select Data From MySQLi Procedural(MySQL Select Query)

  $database_host = 'localhost'; // database host name
    // if using port then add port $database_host = 'localhost:3036'; 
    $database_user = 'database_user'; // database user name
    $database_pass = 'database_password'; // database user password
$database_name = 'onlinecode_db';  // database name

// connect with database
$database_conn = mysqli_connect($database_host, $database_user, $database_pass, $database_name);

// check database connection
if (!$database_conn)
{
    // error in database connection
    die("Could not connect to database : " . mysqli_connect_error());
}
    
$sql_select_query = 'SELECT id,first_name,last_name,user_email FROM user_table';   
$sql_result = mysqli_query($database_conn, $sql_select_query);

if (mysqli_num_rows($sql_result) &gt; 0)
{
    // output data of each row
    while($result = mysqli_fetch_assoc($sql_result)) {
        echo "User ID :{$result['id']}".
         "First Name : {$result['first_name']}".
         "Last Name : {$result['last_name']}".
         "Email Address : {$result['user_email']}";
    }
}
else
{
    echo "No data found";
}

// close connection with MySQLi Procedural
mysqli_close($database_conn);

PHP Select Data From PDO with Prepared Statements(MySQL Select Query)

 
 $database_host = 'localhost'; // database host name  
    $database_user = 'database_user'; // database user name
    $database_pass = 'database_password'; // database user password
$database_name = 'onlinecode_db'; // database name

try
{
    $database_conn = new PDO("mysql:host=$database_host;dbname=$database_name", $database_user, $database_pass);
    // if using port then use port id in PDO
    //$database_conn = new PDO('mysql:host=$database_host;port=5432;dbname=$database_name', $database_user, $database_pass);
   
    // exception for PDO connection error
    $database_conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   
    $sql_select_query = 'SELECT id,first_name,last_name,user_email FROM user_table';

    $database_conn-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $database_conn-&gt;prepare($sql_select_query);
    $stmt-&gt;execute(); // execute stmt

    // set the resulting(stmt result) array to associative
    $result = $stmt-&gt;setFetchMode(PDO::FETCH_ASSOC);
    foreach(new TableRows(new RecursiveArrayIterator($stmt-&gt;fetchAll())) as $key=&gt;$values)
    {
        echo $key." = ".$values;
    }
}
catch(PDOException $exception)
{
    // error in database connection
    echo "Could not connect to database : " . $exception-&gt;getMessage(); // exception
}

// close connection with PDO
$database_conn = null;


how to connect database with mysql, MySQLi , pdo – php

how to connect database with mysql, MySQLi , pdo in php

Mysql database connection

$database_host = 'localhost'; // database host name
// if using port then add port $database_host = 'localhost:3036'; 
$database_user = 'database_user'; // database user name
$database_pass = 'database_password'; // database user password

// connect with database
$database_conn = mysql_connect($database_host, $database_user, $database_pass);

// check database connection
if(! $database_conn )
{
    // error in database connection
    die('Could not connect to database : ' . mysql_error());
}
// connected to database
echo 'Connected successfully with database';

// close connection with Mysql database
mysql_close($database_conn);  



MySQLi Object-Oriented database connection

$database_host = 'localhost'; // database host name
// if using port then add port $database_host = 'localhost:3036'; 
$database_user = 'database_user'; // database user name
$database_pass = 'database_password'; // database user password

// connect with database
$database_conn = new mysqli($database_host, $database_user, $database_pass);

// check database connection
if ($database_conn->connect_error)
{  
    // error in database connection
    die("Could not connect to database : " . $database_conn->connect_error);
}

// connected to database
echo 'Connected successfully with database';

// close connection with MySQLi database
$database_conn->close();

MySQLi Procedural database connection

$database_host = 'localhost'; // database host name
// if using port then add port $database_host = 'localhost:3036'; 
$database_user = 'database_user'; // database user name
$database_pass = 'database_password'; // database user password

// connect with database
$database_conn = mysqli_connect($database_host, $database_user, $database_pass);

// check database connection
if (!$database_conn)
{
    // error in database connection
    die("Could not connect to database : " . mysqli_connect_error());
}

// connected to database
echo 'Connected successfully with database';

// close connection with MySQLi Procedural
mysqli_close($database_conn);

PDO database connection

$database_host = 'localhost'; // database host name   
$database_user = 'database_user'; // database user name
$database_pass = 'database_password'; // database user password
$database_name = 'your_database_name'; // database name

try
{
    $database_conn = new PDO("mysql:host=$database_host;dbname=$database_name", $database_user, $database_pass);
    // if using port then use port id in PDO 
    //$database_conn = new PDO('mysql:host=$database_host;port=5432;dbname=$database_name', $database_user, $database_pass);
    
    // exception for PDO connection error
    $database_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // connected to database
    echo 'Connected successfully with database';
}
catch(PDOException $exception)
{
    // error in database connection
    echo "Could not connect to database : " . $exception->getMessage(); // exception
}

// close connection with PDO
$database_conn = null;



PHP – send email with attachment file

how to send email with attachment file in PHP

In this post we will show you how to send email with attachment in php. by using this following code is used for send email with attachment in php. following code will sending pdf file in email.

$file_name = "example.pdf"; // attachment file name
$path = "folder_name"; // path of attachment file
$user_name = "user name"; // user name
$mail_to = "onlinecode@email.com"; // to eamil
$email_subject = "Notification of attachment for user"; // subject of eamil
$body_text = "Hello ".$user_name.",\nThis demo message with file attachment. You will be notified when their review has been completed.\n Regard \n onlinecode Team";

$attachment_file = $path . "/" . $file_name; // path of file
$attachment_file_size = filesize($attachment_file);
$email_handle = fopen($attachment_file, "r");
$content = fread($email_handle, $attachment_file_size);
fclose($email_handle);// file close of email handle
$content = chunk_split(base64_encode($content));
$time_separator = md5(time());// a random hash will be necessary to send mixed content

// carriage return type (we use a PHP end of line constant)
$email_eol = PHP_EOL;
$body_message = $body_text;
// main header (multipart mandatory)
$email_headers = "From: onlinecode.org Team &lt;onlinecode@email.co&gt;" . $email_eol;
// sender eamil detail
$email_headers .= "MIME-Version: 1.0" . $email_eol;//MIME-Version
$email_headers .= "Content-Type: multipart/mixed; boundary=\"" . $time_separator . "\"" . $email_eol;//Content-Type
$email_headers .= "Content-Transfer-Encoding: 7bit" . $email_eol;//Content-Transfer-Encoding
$email_headers .= "This is a MIME encoded message." . $email_eol;

// eamil message
$email_headers .= "--" . $time_separator . $email_eol;
$email_headers .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $email_eol;
$email_headers .= "Content-Transfer-Encoding: 8bit" . $email_eol;
$email_headers .= $body_message . $email_eol;

// attachment
$email_headers .= "--" . $time_separator . $email_eol;
$email_headers .= "Content-Type: application/octet-stream; name=\"" . $file_name . "\"" . $email_eol;
$email_headers .= "Content-Transfer-Encoding: base64" . $email_eol;
$email_headers .= "Content-Disposition: attachment" . $email_eol;
$email_headers .= $content . $email_eol;
$email_headers .= "--" . $time_separator . "--";
mail($mail_to, $email_subject, ", $email_headers); //SEND Mail TO USER

insert category programmatically in magento

insert category programmatically in magento

In this post we’ll show you how to magento insert category programmatically using magento. By using following code we can insert category programmatically and this code also work in exteranl magen to file.

$parentId = '2'; // prenet catagory
try{
    $category = Mage::getModel('catalog/category');
    $category->setName('category-name'); // category name
    //$category->setUrlKey('your-category-url-key'); // url key
    $category->setIsActive(1); // is active
    $category->setDisplayMode('PRODUCTS');
    $category->setIsAnchor(1); //for active anchor
    $category->setStoreId(Mage::app()->getStore()->getId());
    $_parent_category = Mage::getModel('catalog/category')->load($parentId);
    $category->setPath($_parent_category->getPath());
    $cat_data= $category->save(); // insert catagory
    //echo $cat_data->getEntityId();// print catagory id
}
catch(Exception $e)
{
    print_r($e);//Exception in insert catagory
}

 

customer registration programmatically in Magento code from an external php file

customer registration programmatically in Magento code from an external php file

In this post we’ll show you how to customer registration programmatically in magento using with exteranl php file. By using following code we can register user and create seeeion on user or customer.
  • This post is use for register user or customer registration programmatically in Magento.
  • first we create user ,if user is not exist then insert data into database then we will go for login to user programmatically.
  • add you detail in variable and enjoy the code.
set_time_limit(0);
ini_set('memory_limit', '1024M');
include_once "app/Mage.php";  // Mage file include
include_once "downloader/Maged/Controller.php"; // Controller file include
error_reporting(E_ALL | E_STRICT);

$website_Id = Mage::app()->getWebsite()->getId();
$store_detail = Mage::app()->getStore();

$setFirstname = "Firstname"; // add  First name
$setLastname = "setLastname"; // add Last name
$setEmail = "Ttest123@gm.co"; // add  Email id
$setPassword = "password@789"; // add  password
/*$setPostcode = "989898"; // add  Post code
$setCity = "Sydney "; // add  city of user
$setRegion = "New South Wales";
$setTelephone = "99999999999";
$setFax = "123456";
$setCompany = "Australia";
$setStreet = "in Australia some place";*/
$customer = Mage::getModel("customer/customer");
$customer ->setWebsiteId($website_Id)
->setStore($store_detail)
->setFirstname($setFirstname)
->setLastname($setLastname)
->setEmail($setEmail)
->setPassword($setPassword);
try{
    $results = $customer->save();   
    $getEntityId = $results->getEntityId(); // get user id
}
catch (Exception $e) {
    // bug or user is exist
    echo $e->getMessage(); // print Exception Message
}

Mage::getSingleton('core/session', array('name' => 'frontend'));

$sessionCustomer = Mage::getSingleton("customer/session");
$red_url = "http://www.onlinecode.org/";
if($sessionCustomer->isLoggedIn()) {
    header('Location: '. $red_url);
    break;
}
else{
    //echo $setEmail." ".$setPassword;
    loginUser($setEmail,$setPassword);
    //header('Location: '. $red_url);
    //break;
}
// function for login user programmatically
function loginUser($email,$password){
    umask(0);
    ob_start();
    session_start();
    Mage::app('default');
    Mage::getSingleton("core/session", array("name" => "frontend"));
    $website_Id = Mage::app()->getWebsite()->getId();
    $store_detail = Mage::app()->getStore();
    $customer_detail = Mage::getModel("customer/customer");
    $customer_detail->website_id = $website_Id;
    $customer_detail->setStore($store_detail);
    try
    {
        $customer_detail->loadByEmail($email);
        $session = Mage::getSingleton('customer/session')->setCustomerAsLoggedIn($customer_detail);
        $session->login($email,$password);
    }
    catch(Exception $e)
    {
        echo $e->getMessage();// print Exception Message
    }
}

Customer / user registration programmatically in Magento

$website_Id = Mage::app()->getWebsite()->getId();
$store_detail = Mage::app()->getStore();

$setFirstname = "Firstname"; // add  First name
$setLastname = "setLastname"; // add Last name
$setEmail = "Ttest123@gm.co"; // add  Email id
$setPassword = "password@789"; // add  password
/*$setPostcode = "989898"; // add  Post code
$setCity = "Sydney "; // add  city of user
$setRegion = "New South Wales";
$setTelephone = "99999999999";
$setFax = "123456";
$setCompany = "Australia";
$setStreet = "in Australia some place";*/
$customer = Mage::getModel("customer/customer");
$customer ->setWebsiteId($website_Id)
->setStore($store_detail)
->setFirstname($setFirstname)
->setLastname($setLastname)
->setEmail($setEmail)
->setPassword($setPassword);
try{
    $results = $customer->save();   
    $getEntityId = $results->getEntityId(); // get user id
}
catch (Exception $e) {
    // bug or user is exist
    echo $e->getMessage(); // print Exception Message
}

Mage::getSingleton('core/session', array('name' => 'frontend'));

$sessionCustomer = Mage::getSingleton("customer/session");
$red_url = "http://www.onlinecode.org/";
if($sessionCustomer->isLoggedIn()) {
    header('Location: '. $red_url);
    break;
}
else{
    //echo $setEmail." ".$setPassword;
    loginUser($setEmail,$setPassword);
    //header('Location: '. $red_url);
    //break;
}
// function for login user programmatically
function loginUser($email,$password){
    umask(0);
    ob_start();
    session_start();
    Mage::app('default');
    Mage::getSingleton("core/session", array("name" => "frontend"));
    $website_Id = Mage::app()->getWebsite()->getId();
    $store_detail = Mage::app()->getStore();
    $customer_detail = Mage::getModel("customer/customer");
    $customer_detail->website_id = $website_Id;
    $customer_detail->setStore($store_detail);
    try
    {
        $customer_detail->loadByEmail($email);
        $session = Mage::getSingleton('customer/session')->setCustomerAsLoggedIn($customer_detail);
        $session->login($email,$password);
    }
    catch(Exception $e)
    {
        echo $e->getMessage();// print Exception Message
    }
}

Tuesday, January 3

PHP – how to Convert JPG-GIF image to PNG?


PHP – how to Convert JPG-GIF image to PNG formart

In this post we will show you how to JPG-GIF image to PNG in php . hear we use imagepng() for conver image formart.

How to use it imagepng()::

imagepng(imagecreatefromstring(file_get_contents($filename)), "output.png");

You would use $_FILES["user_image"]["tmp_name"] for the user_image(for get file name from user), and a different output user_image obviously. But the image format probing itself become redundant.

Method :: 1 # Convert JPG/GIF image to PNG using if-else

 <!-- Convert JPG/GIF image to PNG --->
<form method="post" enctype="multipart/form-data">
    <p>Convert JPG/GIF image to PNG</p><br>
    <input type="file" name="user_image" /><br>
    <input type="submit" name="submit" value="Submit" />
</form>

<?php
// submit button press/hit
if(isset($_POST['submit']))
{
    if(exif_imagetype($_FILES['user_image']['tmp_name']) ==  IMAGETYPE_GIF)
    {
        // Convert GIF to png image type
        $new_png_img = 'user_image.png';
        $png_img = imagepng(imagecreatefromgif($_FILES['user_image']['tmp_name']), $new_png_img);
    }
    elseif(exif_imagetype($_FILES['user_image']['tmp_name']) ==  IMAGETYPE_JPEG)
    {
        // Convert JPG/JPEG to png image type
        $new_png_img = 'user_image.png';
        $png_img = imagepng(imagecreatefromjpeg($_FILES['user_image']['tmp_name']), $new_png_img);
    }
    else
    {
        // already png image type
        $new_png_img = 'user_image.png';
    }      
}
?>

 

Method :: 2 # Convert JPG/GIF image to PNG using switch case

 

<!-- Convert JPG/GIF image to PNG --->
<form method="post" enctype="multipart/form-data">
    <p>Convert JPG/GIF image to PNG</p><br>
    <input type="file" name="user_image" /><br>
    <input type="submit" name="submit" value="Submit" />
</form>

<?php
// submit button press/hit
if(isset($_POST['submit']))
{
    $conver_image = $_FILES['user_image']['tmp_name'];
    $extension = pathinfo($conver_image, PATHINFO_EXTENSION);
    switch ($extension) {
        case 'jpg':
        case 'jpeg':
           $set_image = imagecreatefromjpeg($conver_image);
        break;
        case 'gif':
           $set_image = imagecreatefromgif($conver_image);
        break;
        case 'png':
           $set_image = imagecreatefrompng($conver_image);
        break;
    }

    imagepng($set_image, $new_conver_image);
}
?>



QR code – How to generate QR code in php

How to generate QR code in PHP

In this post we will generate QR code (Quick Response Code) using php. QR code is used to read data with smart devices for easy.
Hear pass you uel and it will generate qr code of you url.

<?php
// include QR Generator class
include "QRGenerator.php";

// check for post method call.
if($_SERVER["REQUEST_METHOD"] === "POST")
{
    $set_url = $_POST['set_url'];
    $set_size = $_POST['set_size'];
    $example_1 = new QRGenerator($set_url,$set_size);
    $qr_img_1 = "<img src=".$example_1->generate().">";
    $html_content ='<form method="post" action="">
        <table>
            <tr>
                <td colspan="2">'.$qr_img_1.'</td>
            </tr>         
            <tr>
                <td>Text/URL</td>
                <td><input type="text" name="url" /></td>
            </tr>         
            <tr>
                <td>Size</td>
                <td><input type="text" name="size" /> <i>min: 100 and max: 800</i></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="submit" name="generate" value="Generate" /></td>
            </tr>
        </table>
    </form>';
}
else
{
    $html_content ='<form method="post" action="">
    <table>
        <tr>
            <td>Text/URL</td>
            <td><input type="text" name="set_url" /></td>
        </tr>         
        <tr>
            <td>Size</td>
            <td><input type="text" name="set_size" /></td>
        </tr>
        <tr>
            <td rowspan="2"><i>min: 80 and max: 800</i></td>
        </tr>
        <tr>          
            <td>
                <input type="submit" name="generate" value="Generate" />
            </td>
            <td>
                <input type="reset" name="reset" value="reset" />
            </td>
        </tr>
    </table></form>';
    $example_1 = new QRGenerator('http://onlinecode.org',100);
    $qr_img_1 = "<img src=".$example_1->generate().">";
     
    $example_2 = new QRGenerator('https://in.yahoo.com/',100);
    $qr_img_2 = "<img src=".$example_2->generate().">";

    $example_3 = new QRGenerator('https://www.google.com/',100,'ISO-8859-1');
    $qr_img_3 = "<img src=".$example_3->generate().">";

    $example_4 = new QRGenerator('https://www.bing.com',100,'ISO-8859-1');
    $qr_img_4 = "<img src=".$example_4->generate().">";

    $html_content .='
    <table>
        <tr>
            <td>'.$qr_img_1.'</td>
            <td>'.$qr_img_2.'</td>
        </tr>         
        <tr>
            <td>'.$qr_img_3.'</td>
            <td>'.$qr_img_4.'</td>
        </tr>
    </table>';
}
$pre = 1;
$page_title = "How to generate QR code in PHP | onlinecode";
$page_heading = "How to generate QR code in PHP example - onlinecode";
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>
            <?php
                // add page title
                echo $page_title;
            ?>
        </title>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <style type="text/css">
          img {border-width: 0}
          * {font-family:'Lucida Grande', sans-serif;}
        </style>
    </head>
    <body>
        <div>
            <h2>
                <?php
                    // add page heading
                    echo $page_heading;
                ?>
            </h2>
            <p>
                <!-- add this tag after last badge tag -->
                <script type="text/javascript">
                    (function() {
                        var qr_var = document.createElement('script');
                        // assign javascript
                        qr_var.type = 'text/javascript';
                        // assign async
                        qr_var.async = true;
                        // assign javascript                    
                        qr_var.src = 'https://apis.google.com/js/plusone.js';
                        // get script
                        var get_script = document.getElementsByTagName('script')[0];
                        get_script.parentNode.insertBefore(qr_var, get_script);
                    })();
                </script>
        </div>
        <hr />     
        <p>
        <?php
            if(!isset($pre)) {
        ?>
            <pre>
                <?php
                    print_r($html_content);
                ?>
            </pre>
        <?php } else  { ?>
            <pre>
                <?php
                    print_r($html_content);
                ?>
            </pre>   
        <?php  } ?>
        </p>
    </body>
</html>

class of QRGenerator

 <?php
// assign class QRGenerator
class QRGenerator {
    // assign protected variable
    protected $qr_size;
    protected $qr_data;
    protected $qr_encoding;
    protected $qr_errorCorrectionLevel;
    protected $qr_marginInRows;
    protected $qr_debug;
  
    // assign construct
    public function __construct($qr_data='http://onlinecode.org',$qr_size='100',$qr_encoding='UTF-8',$qr_errorCorrectionLevel='L',$qr_marginInRows=4,$qr_debug=false)
    {        
        $this->qr_data = urlencode($qr_data);
        $this->qr_size = ($qr_size>80 && $qr_size<800)? $qr_size : 100;
      
        $this->qr_encoding = ($qr_encoding == 'Shift_JIS' || $qr_encoding == 'ISO-8859-1' || $qr_encoding == 'UTF-8') ? $qr_encoding : 'UTF-8';
      
        $this->qr_errorCorrectionLevel = ($qr_errorCorrectionLevel == 'L' || $qr_errorCorrectionLevel == 'M' || $qr_errorCorrectionLevel == 'Q' || $qr_errorCorrectionLevel == 'H') ?  $qr_errorCorrectionLevel : 'L';
      
        $this->qr_marginInRows=($qr_marginInRows>0 && $qr_marginInRows<10) ? $qr_marginInRows:4;
        $this->qr_debug = ($qr_debug==true)? true:false;   
    }
    // function generate
    public function generate()
    {        
        $QRLink = "https://chart.googleapis.com/chart?cht=qr&chs=".$this->qr_size."x".$this->qr_size.               
                   "&chl=" . $this->qr_data .
                   "&choe=" . $this->qr_encoding .
                   "&chld=" . $this->qr_errorCorrectionLevel . "|" . $this->qr_marginInRows;
        if ($this->qr_debug)
        {
            echo $QRLink;
        }
        return $QRLink;
    }
}
?>

 

Ubuntu – How To Install Linux, Apache, MySQL, PHP (LAMP) stack

How To Install Linux, Apache, MySQL, PHP (LAMP) stack on Ubuntu

The following instructional exercise presumes you comprehend what a LAMP(Linux, Apache, MySQL, PHP) Server is, the means by which to work a site from the back end and how to introduce programming utilizing either the Software Center or the Terminal.

It additionally expect encounter running other Basic Terminal Commands.

There is additionally a phenomenal article on Digital Ocean that might be of more pertinence on the off chance that you are taking a shot at a remote or open confronting server.

1. Introduce Apache

To install Apache you should install the Metapackage apache2. This should be possible via hunting down and introducing in the Software Center, or by running the following order.

1
sudo apt-get install apache2
 
2. Install MySQL

To Install MySQL you should Install the Metapackage mysql-server. This should be possible via hunting down and introducing in the Software Center, or by running the following command.
1
sudo apt-get install mysql-server
 
3. Introduce PHP

To introduce PHP you should introduce the Metapackages php5 and libapache2-mod-php5. This should be possible via hunting down and introducing in the Software Center, or by running the following command.

1
sudo apt-get install php5 libapache2-mod-php5
 
4. Restart Server 

Your server ought to restart Apache consequently after the establishment of both MySQL and PHP. In the event that it doesn’t, execute this command.
1
sudo /etc/init.d/apache2 restart

5. Check Apache
Open a web program and explore to http://localhost/. You ought to see a message saying It works!

6. Check PHP
You can check your PHP by executing any PHP record from inside /var/www/. On the other hand you can execute the following command, which will make PHP run the code without the requirement for making a record.
 
1
php - r 'echo "sucess :: Your PHP installation is working fine. thanks to onlinecode.org";'

remove .php, .html, .htm extensions using .htaccess

htaccess – How to remove .php, .html, .htm extensions with .htaccess

we are going to show you how to remove .php, .html, .htm extensions with .htaccess file.

Remove .php, .html, .htm Extensions

To remove the .php extension from a PHP file as an example your-domain.com/your-page.php to your-domain.com/your-page you’ve got to feature the subsequent code within the .htaccess file ::

RewriteEngine On
RewriteCond % !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

If we would like to get rid of the .html extension from a HTML file as an example your-domain.com/your-page.html to your-domain.com/your-page you just ought to alter the last line from the code higher than to match the computer filename ::

RewriteRule ^([^\.]+)$ $1.html [NC,L]

That’s it! you’ll currently link pages within the HTML document without having to feature the extension of the page.

example:

<a href="http://your-domin-name.com/your-dir" title="your-dir">NAME-OF-LINK</a>

Adding a trailing slash at the tip

I received several requests asking a way to add a trailing slash at the tip. Ignore the primary piece and insert the subsequent code.

The primary four lines modify the removal of the extension and therefore the following, with the addition of the trailing slash and redirecting.

Link to the HTML or PHP file as shown higher than. Don’t forget to alter the code if you would like it applied to associate HTML file.

RewriteEngine On
RewriteCond % !-f
RewriteRule ^([^/]+)/$ $1.php
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php
RewriteCond % !-f
RewriteCond % !-d
RewriteCond % !(\.[a-zA-Z0-9]|/)$
RewriteRule (.*)$ /$1/ [R=301,L]
 
Some individuals asked however you’ll take away the extension from each HTML and PHP files. I haven’t got a writing resolution for that.
But, you’ll simply modification the extension of your HTML file from .html or .htm to .php and add the code for removing the .php extension.

Conclusion for Removing Extensions

For those that don’t seem to be thus skilled with .htaccess files there’s an internet tool for making .htaccess files. it’s pretty smart for novice users and really straightforward to use. Visit their web site.

Note For GoDaddy User

Attention For GoDaddy users only ::

so as to get rid of the extensions you wish to modify MultiViews before.

The code ought to appear as if this ::

Options +MultiViews
RewriteEngine On
RewriteCond % !-d
RewriteCond % !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

If you’re disquieted that search engines may index these pages as duplicate content, add a canonical meta tag in your HTML head :: 

<link rel="canonical" href="https://your-domin-name.com/your-dir/other-data">

 

 


php – connect multiple databases databases in single webpage

mysql connect multiple databases in single webpage using php you will learn how to select the records from connect multiple databases tables using the SQL SELECT query in PHP.

1st database
database name :: onlinecode_db_one
table name :: user_table_one
+----+------------+-----------+-----------------------------+
| id | first_name | last_name | user_email                  | // column name
+-----------+------------+-----------+----------------------+
| 1  | Peter      | Kong      | peterKong@mail.com          |
| 2  | John       | smith     | johnsmith@mail.com          |
| 3  | Shuvo      | Kent      | Shuvokent@mail.com          |
| 4  | nick       | Habib     | nickHabib@mail.com          |
| 5  | Anthony    | Potter    | Anthonypott@mail.com        |
+-----------+------------+-----------+----------------------+

2st database
database name :: onlinecode_db_two
table name :: user_table_two
+----+------------+-----------+-----------------------------+
| id | first_name | last_name | user_email                  | // column name
+-----------+------------+-----------+----------------------+
| 1  | Peter      | Kent      | peterKong@mail.com          |
| 2  | John       | Habib     | johnsmith@mail.com          |
| 3  | Shuvo      | Kong      | Shuvokent@mail.com          |
| 4  | max        | smith     | johnHabib@mail.com          |
| 5  | Anthony    | Potter    | Anthonypott@mail.com        |
+-----------+------------+-----------+----------------------+

$database_host = 'localhost'; // database host name
// if using port then add port $database_host = 'localhost:3036'; 
$database_user = 'database_user'; // database user name
$database_pass = 'database_password_one'; // database user password
$database_name = 'onlinecode_db_one';  // database name

// connect with database
$database_conn_one = mysql_connect($database_host, $database_user, $database_pass);

// check database connection
if(! $database_conn_one )
{
    // error in database connection
    die('Could not connect to database : ' . mysql_error());
}



$database_host = 'localhost'; // database host name
// if using port then add port $database_host = 'localhost:3036'; 
$database_user = 'database_user'; // database user name
$database_pass = 'database_password_two'; // database user password
$database_name = 'onlinecode_db_two';  // database name

// connect with database
$database_conn_two = mysql_connect($database_host, $database_user, $database_pass);

// check database connection
if(! $database_conn_two )
{
    // error in database connection
    die('Could not connect to database : ' . mysql_error());
}

// select query form 1st data base "onlinecode_db_one"
$sql_select_query_one = 'SELECT id,first_name,last_name,user_email FROM user_table';

mysql_select_db($database_name_one);
$sql_result_one = mysql_query( $sql_select_query_one, $database_conn_one );
if(! $sql_result_one )
{
    // error in sql query or Fetch data
    die('Could not get data: ' . mysql_error());
}
while($result = mysql_fetch_array($sql_result_one, MYSQL_ASSOC))
{
    echo "User ID :{$result['id']}".
      "First Name : {$result['first_name']}".
      "Last Name : {$result['last_name']}".
      "Email Address : {$result['user_email']}";
}
echo "Get data successfully";

// close connection with Mysql database
mysql_close($database_conn_one);


// select query form 2st data base "onlinecode_db_two"
$sql_select_query_two = 'SELECT id,first_name,last_name,user_email FROM user_table';

mysql_select_db($database_name_two);
$sql_result_two = mysql_query( $sql_select_query_two, $database_conn_two );
if(! $sql_result_two )
{
    // error in sql query or Fetch data
    die('Could not get data: ' . mysql_error());
}
while($result = mysql_fetch_array($sql_result_two, MYSQL_ASSOC))
{
    echo "User ID :{$result['id']}".
      "First Name : {$result['first_name']}".
      "Last Name : {$result['last_name']}".
      "Email Address : {$result['user_email']}";
}
echo "Get data successfully";

// close connection with Mysql database
mysql_close($database_conn_two); 

10 Best Chatting Apps In India

  The modern world is all about Internet. There was a time when people use to pay high telephone bills to stay in touch with their friends a...