Showing posts with label projects. Show all posts
Showing posts with label projects. Show all posts

Friday, March 13, 2015

Creating a simple search engine using Javascript

Before we start, you must have a little knowledge on functions in JavaScript and some basic HTML tags. If you are still unknown about these things you may copy the example here but you wont be able to modify it for your purpose of use, so please refer to JavaScript and HTML official web site for details in them and get some time to study functions and basic tags.

For those who already carry information on JavaScript and HTML, here we go. Firstly lets us sketch the skeleton for our search user interface.


search.html
[Note: please fill in other validating tags for a complete HTML file]

 <table width ="200" border="0" cellspacing="0">  
 <tr>  
 <td colspan="2">Sarch </td>  
 </tr>  
 <tr>  
 <td>  
 <input type="text" name="query" size="100">  
 </td>  
 <td>  
 <input type="button" name="Search" value="GO">  
 </td>  
 </tr>  
 </table>  



after we are done with html now we go to JavaScript Section, here we first create a function that does search as it is the vital function for our project.

 //For commencing search  
 function doSearch ( s ) {  
 openDbRelativeURL("All?SearchView&Query=" + s.value);  
 }  

Now as we have done our doSearch function

 function doSearch ( s ) {  
 var regExp1 = /\bfield\b/;  
 var regExp2 = /[(,),<,>,\[,\]]/;  
 var str = s.value; if ( str == "" ){  
 alert("Please be sure to enter something to search for.");  
 s.focus();  
 } else {  
 if ( typeof regExp1.source != 'undefined' ) //supports regular expression testing  
 if ( regExp1.test( str ) || regExp2.test( str ) ){  
 var alrt = "Please note that you can not include:";  
 alrt += "\n\nThe reserved word 'field'\nthe characters [, ], (, ), < or >";  
 alrt += "\n\nin your search query!\n\nIf you are confident that you know";  
 alrt += "\nwhat you are doing, then you can\nmanually produce the URL required."  
 s.focus();  
 return alert( alrt );  
 }  
 openDbRelativeURL("All?SearchView&Query=" + escape( str ) + "&start=1&count=10");  
 }  
 } 

after dosearch function the components that are searched should be displayed by finding it so we create another function  openDBRelative URL

 //For opening the related URL  
 function openDbRelativeURL( url, target ){  
 //Check we have a target window;  
 target = (target == null ) ? window : target;  
 //Work out the path of the database;  
 path = location.pathname.split('.nsf')[0] + '.nsf/';  
 target.location.href = path + url;  
 }


Lastly Paste these codes inside <script> </script> tags inside your html file or include them providing link.

[Note: I haven't checked this example in m local machine or live server.... might work please let me informed if something goes wrong]





Wednesday, December 24, 2014

Restful webservice Application in PHP

Firstly let me be clear about the environment and requirements for the project. The required materials for the project are:

  1. IDE fully supportive for PHP
  2. A local Web Server (WAMP,XAMPP etc.) as per your O/S and easiness. 
  3. Google Chrome web browser with an extinction Advance rest Client.
Now if we have all this things with us we are ready to start. The basic functioning that our "Restfull Web Service " will be registering a user, loging a user along with some other functionalities that shall be brodened later.



Now lets create a database as per our requirement . Create a database "rest". Inside SQL insert the below code :

USE rest;
CREATE TABLE rest (username varchar(15) , password varchar (15), email varchar (50), status varchar (80));


The first thing we need to do is; create a folder "rest"  inside your web server after that lets create a file"DB_Config" that will enable us to connect to our database.

(DB_Config.php)

 <?php  
 /**  
  * Created by PhpStorm.  
  * User: wao  
  * Date: 1/26/2015  
  * Time: 4:28 PM  
  */  
 $mysql_hostname = "localhost"; /* replace it with your host [In most case the host name is same "localhost"] */  
 $mysql_user = "root"; /*It is a default username in your MySQL if you have set manual users please replace "root"*/  
 $mysql_password = "";/*It is a default password in your MySQL if you have set manual password please replace ""*/  
 $mysql_database = "rest"; /* insert your database name here*/  
 $bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)  
 or die("Opps some thing went wrong, couldnot connect to the database");  
 mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong, cannot select database");  
 ?> 


After we are done with DB_Config.php file we will now create a next file namely "signup.php" 


 <?php  
 // Include confi.php  
 include_once('DB_Config.php');  
 if($_SERVER['REQUEST_METHOD'] == "POST"){  
  // This code gets data  
  $username = isset($_POST['username']) ? mysql_real_escape_string($_POST['username']) : "";  
  $email = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : "";  
  $password = isset($_POST['password']) ? mysql_real_escape_string($_POST['password']) : "";  
  $status = isset($_POST['status']) ? mysql_real_escape_string($_POST['status']) : "";  
  // Below script inserts data into data base  
  $sql = "INSERT INTO `rest`.`users` (`ID`, `username`, `email`, `password`, `status`) VALUES (NULL, '$username', '$email', '$password', '$status');";  
  $qur = mysql_query($sql);  
  if($qur){  
  $json = array("status" => 1, "msg" => "Done User created!");  
  }else{  
  $json = array("status" => 0, "msg" => "Error creating user!");  
  }  
 }else{  
  $json = array("status" => 0, "msg" => "Request method not accepted");  
 }  
 @mysql_close($conn);  
 /* Output header */  
  header('Content-type: application/json');  
  echo json_encode($json);  
  ?>  

After finishing with "signup.php" we wil now create another file "login.php"


 <?PHP  
 include_once('DB_Config.php');  
 if($_SERVER['REQUEST_METHOD'] == "POST"){  
  // Get data  
  $username = isset($_POST['username']) ? mysql_real_escape_string($_POST['username']) : "";  
  $password = isset($_POST['password']) ? mysql_real_escape_string($_POST['password']) : "";  
  // Insert data into data base  
  $sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";  
  $qur = mysql_query($sql);  
  $count=mysql_num_rows($qur);  
  if($count == 1)  
  {  
  $json=array("status"=>1, "msg"=>"user logged in");  
  }else{  
  $json=array("status"=>0, "msg"=>"user not loggedin!either password doesnot match or u have other error");  
  }  
 }else{  
  $json = array("status" => 0, "msg" => "Request method not accepted");  
  }  
 @mysql_close($conn);  
 /* Output header */  
  header('Content-type: application/json');  
  echo json_encode($json);  
  ?> 

     Open Google Chrome and run Advance Rest Client , and please refer to the snapshot for checking your webservice restfull application.


Download Source Code
    
restful web service php

MySQL database connection script for PHP

This is a very useful piece of script, somehow these days MySQL gives depreciating error  as PDO has replaced it.Though it hasn't been officially deprecated - due to widespread use - in terms of best practice and education, it might as well be. Please search for PDO DB connection script in this blog under Project and Script.


 <?php  
 /**  
  * Created by PhpStorm.  
  * User: wao  
  * Date: 1/26/2015  
  * Time: 4:28 PM  
  */  
 $mysql_hostname = "localhost"; /* replace it with your host [In most case the host name is same "localhost"] */  
 $mysql_user = "root"; /*It is a default username in your MySQL if you have set manual users please replace "root"*/  
 $mysql_password = "";/*It is a default password in your MySQL if you have set manual password please replace ""*/  
 $mysql_database = "blog"; /* insert your database name here*/  
 $bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)  
 or die("Opps some thing went wrong, couldnot connect to the database");  
 mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong, cannot select database");  
 ?>  

cURL Login to Facebook

Running this cURL script you can anonymously log into your Facebook account for  some penny amount of time. For more details please comment and give feedback or ask questions .


 <?php  
 $post_data['username'] = '###'; /*insert your facebook username/phone number*/  
 $post_data['password'] = '###'; /* your facebook password*/  
 //traverse array and prepare data for posting (key1=value1)  
 foreach ( $post_data as $key => $value) {  
   $post_items[] = $key . '=' . $value;  
 }  
 //create the final string to be posted using implode()  
 $post_string = implode ('&', $post_items);  
 //create cURL connection  
 $curl_connection = curl_init('https://www.facebook.com/login.php');  
 //set options  
 curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);  
 curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");  
 curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);  
 curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);  
 curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);  
 //set data to be posted  
 curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);  
 //perform our request  
 $result = curl_exec($curl_connection);  
 if (stristr($result, "loginerrors"))  
 {  
   echo "There was an error. You were not logged in!";  
 }else{  
   echo "Succes! You were logged in!";  
 }  
 //close the connection  
 curl_close($curl_connection);  
 ?>

Tuesday, December 23, 2014

PDO in PHP

PHP Data Object is what PDO stands for, PDO defines a lightweight, consistent interface that is used for accessing database in PHP. No data functions can be performed or brought in use only using PDO but a database specific PDO driver should be used instead to access a database server. PDO is latest and it is only available  after PHP 5.1 version. PDO makes it easier and convenient and provides a data-access abstraction layer this helps using multiple database  with same function query to fetch the data.

Databases supported by PDO :

Driver name
Supported databases
PDO_CUBRID
Cubrid
PDO_DBLIB
FreeTDS / Microsoft SQL Server / Sybase
PDO_FIREBIRD
Firebird
PDO_IBM
IBM DB2
PDO_INFORMIX
IBM Informix Dynamic Server
PDO_MYSQL
MySQL 3.x/4.x/5.x
PDO_OCI
Oracle Call Interface
PDO_ODBC
ODBC v3 (IBM DB2, unixODBC and win32 ODBC)
PDO_PGSQL
PostgreSQL
PDO_SQLITE
SQLite 3 and SQLite 2
PDO_SQLSRV
Microsoft SQL Server / SQL Azure
PDO_4D
4D


Below here is a simple example of PDO :

Example:

PHP Code(connection.php)

 <?php  
 $dsn = 'mysql:dbname=ft;host=localhost;port=3306';  
 $username = 'root';  
 $password = '';  
 try {  
   $db = new PDO($dsn, $username, $password);  
   if ($db) {  
     echo "Successfully connected to database.";  
   }  
 } catch (PDOException $e) {  
   echo "Could not connect with MySql:" . $e->getMessage();  
 }  
 ?>  
 PHP PDO Insert:  
 PHP Script (insert.php):  
 <?php  
 $dsn = 'mysql:dbname=try;host=localhost;port=3306';  
 $username = 'root';  
 $password = '';  
 try {  
   $db = new PDO($dsn, $username, $password);  
 } catch (PDOException $e) {  
   echo "Could not connect with MySql:" . $e->getMessage();  
 }  
 //PDO Class  
 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);  
 $db->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);  
 //PDO Statement Class  
 $sth = $db->prepare("INSERT INTO test(id, message) VALUES (:id, :mgs)");  
 $data = array(  
   ':id' => 'first',  
   ':msg' => 'this is first message'  
 );  
 echo $sth->execute($data);  
 ?> 
File to get or fetch records ( PHP PDO getting record):

PHP Script (records.php)
 <?php  
 $dsn = 'mysql:dbname=try;host=localhost;port=3306';  
 $username = 'root';  
 $password = '';  
 try {  
   $db = new PDO($dsn, $username, $password);  
 } catch (PDOException $e) {  
   echo "Could not connect with MySql:" . $e->getMessage();  
 }  
 //PDO Class  
 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);  
 $db->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);  
 //PDO Statement Class  
 $sth = $db->query("SELECT * FROM test");  
 print_r($sth->fetch());  
 ?>