Mysql Database Backup Using PHP / Batch File in Windows System.
Posted by Raj
Mysql Database Backup Using PHP / Batch File in Windows System.
In this section, I will show how to backup Mysql database using php script and batch file(.bat).
I had created this script for our client as they require automatic mysql database backup for their project.
So You can schedule below script in task schedular of windows system to backup database on daily /monthly basis.
Example: backup.php
"cd c:\\wamp\\bin\\mysql\\mysql5.5.24\\bin" is the path of Mysql folder.
"mysqldump --opt -h $dbhost -u$dbuser -p$dbpass $dbname>c:\\wamp\\backup\\backup.sql" is the Mysql command used to take backup of mysql database.
It is very easy to backup mysql database using batch file as you have to just write commands in batch file and schedule batch file as per your requirment in Task Shedular.
Example: backup.bat
I hope above examples will help you to take backup of mysql database.
In this section, I will show how to backup Mysql database using php script and batch file(.bat).
I had created this script for our client as they require automatic mysql database backup for their project.
So You can schedule below script in task schedular of windows system to backup database on daily /monthly basis.
Mysql Database Backup Using PHP Script :
Example: backup.php
<?php
ini_set("display_errors",1);
$dbhost = 'localhost'; // Datatbase host name.
$dbuser = 'root'; // Database user name
$dbpass = '123'; // database password
$dbname="testdb"; // database name;
system("cd c:\\wamp\\bin\\mysql\\mysql5.5.24\\bin & mysqldump --opt -h $dbhost -u$dbuser -p$dbpass $dbname>c:\\wamp\\backup\\backup.sql");
?>
"cd c:\\wamp\\bin\\mysql\\mysql5.5.24\\bin" is the path of Mysql folder.
"mysqldump --opt -h $dbhost -u$dbuser -p$dbpass $dbname>c:\\wamp\\backup\\backup.sql" is the Mysql command used to take backup of mysql database.
Mysql Database Backup Using Batch File :
It is very easy to backup mysql database using batch file as you have to just write commands in batch file and schedule batch file as per your requirment in Task Shedular.
Example: backup.bat
cd c:\wamp\bin\mysql\mysql5.5.24\bin
@echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set dt=%%c-%%a-%%b)
mysqldump --opt -h localhost -uroot -p123 testdb>c:\wamp\backup\testdb_%dt%.sql
I hope above examples will help you to take backup of mysql database.
Update Query using joins in MySql
Posted by Raj
Update Query using joins in MySql
In this Article, I will show how to write Mysql update query using joins.You can use multiple tables in your single Update query.
Example :
MySql Query to update employee record whose salary is greater than 50000 and department name is R&D.
MySql Query to delete employee record whose salary is greater than 50000 and department name is R&D.
Updating Query Using Joins in PHP Script:
In this Article, I will show how to write Mysql update query using joins.You can use multiple tables in your single Update query.
Example :
| Departments Table : | |
| id | Name |
| 1 | Accounts |
| 2 | R&D |
| 3 | Sales |
Employees Table : id Name Salary Department Id 1 Rajesh 50000 2 2 Sachin 80000 2 3 Rahul 20000 1
MySql Query to update employee record whose salary is greater than 50000 and department name is R&D.
Update employees
inner join departments ON empoyees.department_id=departments.id
SET employees.salary=40000
WHERE employees.salary>50000 and department.name='R&D'
MySql Query to delete employee record whose salary is greater than 50000 and department name is R&D.
DELETE employees
inner join departments ON empoyees.department_id=departments.id
WHERE employees.salary>50000 and department.name='R&D'
Updating Query Using Joins in PHP Script:
<?php
$host = 'localhost:3036';
$user = 'root';
$pass = 'rootpassword';
$conn = mysql_connect($host, $user, $pass);
mysql_select_db('sampledb');
$sql = "Update employees
join departments ON empoyees.department_id=departments.id
SET employees.salary=40000
WHERE employees.salary>50000 and department.name='R&D'";
$result = mysql_query( $sql, $conn );
echo "data updated successfully\n";
mysql_close($conn);
?>
Create Complex polygon on GMap using Google Maps API v3
Posted by Raj
Create Complex polygon on GMap using Google Maps API v3
In this Section, I will show you how to create polygon on gmap using Google Maps API v3 that has complex edges.This example creates polygon using polyline based on user clicks.I have written this script to create complex geofences.
This example provides everything you need to draw polylines and polygons.You can use the search box to search & zoom location on the map .
1. Click on the gmap to add a Marker.
2. Click on a Marker to remove it.
3. Drag a Marker to move it.
Getting Started :
/**
* Include the Google Maps API JavaScript using a script tag.
*/
/**
* The following code instructs the application to load the Maps API after the page has fully loaded .
*/
/**
* Search and Zoom Location on Map.
*/
}
Example :
This Example will help you to create any shape of polygons on gmap.In next article, I will show you how to integrate Gmaps in Drupal.
In this Section, I will show you how to create polygon on gmap using Google Maps API v3 that has complex edges.This example creates polygon using polyline based on user clicks.I have written this script to create complex geofences.
This example provides everything you need to draw polylines and polygons.You can use the search box to search & zoom location on the map .
How to Draw polygon on Gmap using Google Maps API v3. :
1. Click on the gmap to add a Marker.
2. Click on a Marker to remove it.
3. Drag a Marker to move it.
Getting Started :
/**
* Include the Google Maps API JavaScript using a script tag.
*/
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>/**
* The following code instructs the application to load the Maps API after the page has fully loaded .
*/
function initialize() {
map = new google.maps.Map(document.getElementById("gmap"), {
zoom:13,
center: new google.maps.LatLng(18.520430, 73.856744),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
p = new google.maps.Polygon({
strokeWeight: 3,
fillColor: '#5555FF'
});
p.setMap(map);
p.setPaths(new google.maps.MVCArray([path]));
google.maps.event.addListener(map, 'click', addMarker);
}
/** * Handles click events on a map, and adds a new point to the Polyline.*/
function addMarker(event) {
path.insertAt(path.length, event.latLng); //The path element used to draw polygon and polylines.
var marker = new google.maps.Marker({
position: event.latLng,
map: map,
draggable: true
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
marker.setMap(null);
for (var i = 0, I = markers.length; i < I && markers[i] != marker; ++i);
markers.splice(i, 1);
path.removeAt(i);
}
);
google.maps.event.addListener(marker, 'dragend', function() {
for (var i = 0, I = markers.length; i < I && markers[i] != marker; ++i);
path.setAt(i, marker.getPosition());
}
);
}
/**
* Search and Zoom Location on Map.
*/
function findAddress(address) {
if (!address)
var address=document.getElementById("address").value;
if ((address != '') && geocoder) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
if (results && results[0] && results[0].geometry && results[0].geometry.viewport)
map.fitBounds(results[0].geometry.viewport);
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
Example :
<html>
<title>Create Complex polygon on Gmap using Google Maps API v3</title>
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var poly, map;
var markers = [];
var path = new google.maps.MVCArray;
var geocoder = new google.maps.Geocoder();
function initialize() {
map = new google.maps.Map(document.getElementById("gmap"), {
zoom:13,
center: new google.maps.LatLng(18.520430, 73.856744),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
p = new google.maps.Polygon({
strokeWeight: 3,
fillColor: '#5555FF'
});
p.setMap(map);
p.setPaths(new google.maps.MVCArray([path]));
google.maps.event.addListener(map, 'click', addMarker);
}
function addMarker(event) {
path.insertAt(path.length, event.latLng); //The path element used to draw polygon and polylines.
var marker = new google.maps.Marker({
position: event.latLng,
map: map,
draggable: true
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
marker.setMap(null);
for (var i = 0, I = markers.length; i < I && markers[i] != marker; ++i);
markers.splice(i, 1);
path.removeAt(i);
}
);
google.maps.event.addListener(marker, 'dragend', function() {
for (var i = 0, I = markers.length; i < I && markers[i] != marker; ++i);
path.setAt(i, marker.getPosition());
}
);
}
function findAddress(address) {
if (!address)
var address=document.getElementById("address").value;
if ((address != '') && geocoder) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
if (results && results[0] && results[0].geometry && results[0].geometry.viewport)
map.fitBounds(results[0].geometry.viewport);
} else {
alert("No results found");
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
</script>
</head>
<body style="margin:0px; padding:0px;" onLoad="initialize()">
Find Place: <input type="text" id="address"/><input type="button" value="Go" onClick="findAddress()">
<div id="gmap" style="width:100%; height: 580;"></div>
</body>
</html>
This Example will help you to create any shape of polygons on gmap.In next article, I will show you how to integrate Gmaps in Drupal.
Find second and fourth saturday's of the month in PHP-MySql
Posted by Raj
Find second and fourth saturday's of the month in PHP-MySql
In this section, I have created simple script in PHP to find second(2nd) and fourth(4th) Saturday of the month.
You can use this PHP script to find second and fourth saturday of particular month and year.
In this section, I have created simple script in PHP to find second(2nd) and fourth(4th) Saturday of the month.
<?php
// Mysql Connection
$conn = mysql_connect('localhost','root','');
if (!$conn) {
die('Could not connect to MySQL: ' . mysql_error());
}
echo 'Connection OK'; mysql_close($conn);
// Select Database
mysql_select_db("test");
// Array of the Month's
$month_array=array("jan","Feb","Mar","Apr","May","Jun","july",'Aug',"Sep","Oct","Nov","Dec");
// Array of the Years's
$year_array=array("2013","2014");
foreach($year_array as $year)
{
foreach($month_array as $month)
{
echo $second=date('Y-m-d', strtotime("second sat of $month $year"));
echo "<br>";
echo $fourth=date('Y-m-d', strtotime("fourth sat of $month $year"));
echo "<br>";
}
}
?>
You can use this PHP script to find second and fourth saturday of particular month and year.
php.ini configuration file Default values
Posted by Raj
php.ini configuration file Default values
The PHP configuration file(php.ini) is read when PHP is initialized. php.ini includes the core php.ini directives you can set these directives to configure your PHP setup.php.ini will be located at /etc/php5/apache2/php.ini or /etc/php.ini
;Default Value: On
This determines whether errors should be printed to the screen or not.
---------------------------------------------------------------------
error_reporting
;Default Value: E_ALL & ~E_NOTICE
// Turn off all error reporting
error_reporting(0);
// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);
// Report all PHP errors (see changelog)
error_reporting(E_ALL);
// Report all PHP errors
error_reporting(-1);
--------------------------------------------------------------------------------
max_input_time
;Default Value: -1 (Unlimited)
This sets the maximum time in seconds a script is allowed to parse input data, like POST and GET.
-----------------------------------------------------------------------------------
short_open_tag
;Default Value: On
whether the short form ( ) of PHP's open tag should be allowed
---------------------------------------------------------------------------------
max_execution_time = 30
Maximum execution time of each script, in seconds
----------------------------------------------------------------------------------
file_uploads :"1"
Whether or not to allow HTTP file uploads.
---------------------------------------------------------------------------------
upload_max_filesize : 2M
The maximum size of an uploaded file.
-------------------------------------------------------------------------------
max_file_uploads :20
The maximum number of files allowed to be uploaded simultaneously.
------------------------------------------------------------------------------
max_input_vars : 1000
How many input variables may be accepted .
-------------------------------------------------------------------------------
upload_tmp_dir : NULL
The temporary directory used for storing files when doing file upload.
--------------------------------------------------------------------------------
error_log
Name of the file where script errors should be logged.
------------------------------------------------------------------------------
log_errors : "0"
Tells whether script error messages should be logged to the server's error log
-----------------------------------------------------------------------------------
memory_limit : 128M
This sets the maximum amount of memory in bytes that a script is allowed to allocate.
-----------------------------------------------------------------------------------
session.gc_maxlifetime : 1440
session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage'.
------------------------------------------------------------------------------------
session.cookie_lifetime : 0
session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser.
The value 0 means "until the browser is closed." Defaults to 0.
---------------------------------------------------------------------------------
Check List of php.ini directives: http://php.net/manual/en/ini.list.php
The PHP configuration file(php.ini) is read when PHP is initialized. php.ini includes the core php.ini directives you can set these directives to configure your PHP setup.php.ini will be located at /etc/php5/apache2/php.ini or /etc/php.ini
php.ini default values:
display_errors;Default Value: On
This determines whether errors should be printed to the screen or not.
---------------------------------------------------------------------
error_reporting
;Default Value: E_ALL & ~E_NOTICE
// Turn off all error reporting
error_reporting(0);
// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);
// Report all PHP errors (see changelog)
error_reporting(E_ALL);
// Report all PHP errors
error_reporting(-1);
--------------------------------------------------------------------------------
max_input_time
;Default Value: -1 (Unlimited)
This sets the maximum time in seconds a script is allowed to parse input data, like POST and GET.
-----------------------------------------------------------------------------------
short_open_tag
;Default Value: On
whether the short form ( ) of PHP's open tag should be allowed
---------------------------------------------------------------------------------
max_execution_time = 30
Maximum execution time of each script, in seconds
----------------------------------------------------------------------------------
file_uploads :"1"
Whether or not to allow HTTP file uploads.
---------------------------------------------------------------------------------
upload_max_filesize : 2M
The maximum size of an uploaded file.
-------------------------------------------------------------------------------
max_file_uploads :20
The maximum number of files allowed to be uploaded simultaneously.
------------------------------------------------------------------------------
max_input_vars : 1000
How many input variables may be accepted .
-------------------------------------------------------------------------------
upload_tmp_dir : NULL
The temporary directory used for storing files when doing file upload.
--------------------------------------------------------------------------------
error_log
Name of the file where script errors should be logged.
------------------------------------------------------------------------------
log_errors : "0"
Tells whether script error messages should be logged to the server's error log
-----------------------------------------------------------------------------------
memory_limit : 128M
This sets the maximum amount of memory in bytes that a script is allowed to allocate.
-----------------------------------------------------------------------------------
session.gc_maxlifetime : 1440
session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage'.
------------------------------------------------------------------------------------
session.cookie_lifetime : 0
session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser.
The value 0 means "until the browser is closed." Defaults to 0.
---------------------------------------------------------------------------------
Check List of php.ini directives: http://php.net/manual/en/ini.list.php
MySQL delete duplicate rows from table using single query
Posted by Raj
MySQL delete duplicate rows from table using single query:
In this article,I will show how to delete duplicate records from table using single MySQL Query.
Example:
I have a table contain departments (department_table).
CREATE TABLE IF NOT EXISTS `department_table` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`department` VARCHAR(250) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MYISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Department table contains duplicate records of department.
id Department
1 Sales
2 R&D
3 Support
4 Account
5 Sales
You can use following query to remove duplicate records from table using single query:
DELETE D2
FROM department_table D1
JOIN department_table D2 ON (D2.department = D1.department ) AND( D2.id > D1.id);
OUTPUT:
id Department
1 Sales
2 R&D
3 Support
4 Account
I hope this MySQL query will help you to remove duplicate records from table.
In this article,I will show how to delete duplicate records from table using single MySQL Query.
Example:
I have a table contain departments (department_table).
CREATE TABLE IF NOT EXISTS `department_table` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`department` VARCHAR(250) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MYISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Department table contains duplicate records of department.
id Department
1 Sales
2 R&D
3 Support
4 Account
5 Sales
You can use following query to remove duplicate records from table using single query:
DELETE D2
FROM department_table D1
JOIN department_table D2 ON (D2.department = D1.department ) AND( D2.id > D1.id);
OUTPUT:
id Department
1 Sales
2 R&D
3 Support
4 Account
I hope this MySQL query will help you to remove duplicate records from table.
Most useful jQuery functions
Posted by Raj
Most useful jQuery functions
In this article, I have provided list of most commonly used jQuery functions.
1. jQuery Selectors:
//--- COMMON JQUERY SELECTORS ---//
// get element by id
$("#ElementID").whatever();
// get element by css class
$(".ClassName").whatever();
// get elements where id contains a string
$("[id*='value']").whatever();
// get elements where id starts with a string
$("[id^='value']").whatever();
// get elements where id ends with a string
$("[id$='value']").whatever();
// get all elements of certain type (can use "p", "a", "div" - any html tag)
$("div").whatever();
2. jQuery Toggle, Show and Hide Functions:
//--- JQUERY TOGGLE/SHOW/HIDE ---//
// toggle hide/show of an element
$("#DivID").toggle(1000);
// do something when animation is complete
$("#DivID").toggle(1000, function () {
alert("Toggle Complete");
});
// hide an element
$("#DivID").hide(1000);
// do something when animation is complete
$("#DivID").hide(1000, function () {
alert("Hide Complete");
});
// show an element
$("#DivID").show(1000);
// do something when animation is complete
$("#DivID").show(1000, function () {
alert("Show Complete");
});
3. jQuery Slide Functions:
//--- JQUERY SLIDE - SLIDE AN ELEMENT IN AND OUT ---//
// toggle slide up and down
$("#DivID").slideToggle(1000);
// do something when animation complete
$("#DivID").slideToggle(1000, function () {
alert("Slide Toggle Complete");
});
// slide up
$("#DivID").slideUp(1000);
// do something when animation is complete
$("#DivID").slideUp(1000, function () {
alert("Slide Up Complete");
});
// slide down
$("#DivID").slideDown(1000);
// do something when animation is complete
$("#DivID").slideDown(1000, function () {
alert("Slide Down Complete");
});
4. jQuery Fade Functions:
//--- JQUERY FADE - FADE AN ELEMENT IN, OUT & TO ---//
// fade in
$("#DivID").fadeIn(1000);
// do something when animation complete
$("#DivID").fadeIn(1000, function () {
alert("Fade In Complete");
});
// fade out
$("#DivID").fadeOut(1000);
// do something when animation is complete
$("#DivID").fadeOut(1000, function () {
alert("Fade Out Complete");
});
// fade to (fades to specified opacity)
$("#DivID").fadeTo(1000, 0.25);
// do something when animation is complete
$("#DivID").fadeTo(1000, 0.25, function () {
alert("Fade To Complete");
});
5. jQuery Animate Functions:
//--- ANIMATE (EXAMPLE USES OPACITY, BUT CAN USE ANY CSS PROPERTY. ---//
//--- NOTE SOME MY REQUIRE THE USE OF A PLUGIN SUCH AS JQUERY COLOR ANIMATION PLUGIN. ---//
$("#DivID").animate({ opacity: 0.25 }, 1000);
// do something when animation complete
$("#DivID").animate({ opacity: 0.25 }, 1000, function () {
alert("Opacity Animation Complete");
});
6. Add & Remove CSS Classes:
//--- ADD & REMOVE CSS CLASSES ---///
// add css class
$("#DivID").addClass("newclassname");
// remove css class
$("#DivID").removeClass("classname");
// add & remove class together
$("#DivID").removeClass("classname").addClass("newclassname");
// add & remove multiple classes
$("#DivID").removeClass("classname classname2").addClass("newclassname newclassname2");
7. Get & Set Textbox Values:
//--- GET & SET TEXTBOX VALUE ---//
//--- CAN ALSO BE USED ON ANY OTHER ELEMENT THAT HAS A VALUE PROPERTY ---//
// get the value of a textbox
var TextboxValue = $("#TextboxID").val();
// set the value of a textbox
$("#TextboxID").val("New Textbox Value Here");
8. Get & Set Element's HTML:
//--- GET & SET HTML OF ELEMENT ---//
// get element html
var DivHTML = $("#DivID").html();
// set element html
$("#DivID").html("This is the new html
");
9. Get & Set Element's Text:
//--- GET & SET TEXT OF ELEMENT ---//
// get text of element
var DivText = $("#DivID").text();
// set text of element
$("#DivID").text("This is the new text.");
10. Get & Set Element's Width & Height:
//--- GET & SET ELEMENT'S WIDTH & HEIGHT
// get element height
var ElementHeight = $("#DivID").height();
// set element height
$("#DivID").height(300);
// get element width
var ElementWidth = $("#DivID").width();
// set element width
$("#DivID").width(600);
11. EXTRA: Change Element's CSS Property
//--- CHANGE AN ELEMENT'S CSS PROPERTY ---//
$("#DivID").css("background-color", "#000");
$("#DivID").css("border", "solid 2px #ff0000");
12. each() jQuery API function:
$("#DivID").each(function(index, value) {
console.log('DivID' + index + ':' + $(this).attr('id'));
});
Here is the list of most commonly used jQuery API functions:
find(): Selects elements based on the provided selector string
hide(): Hides an element if it was visible
show(): Shows an element if it was hidden
html(): Gets or sets an inner HTML of an element
append() Injects an element into the DOM after the selected element
prepend() Injects an element into the DOM before the selected element
on(): Attaches an event listener to an element
off() Detaches an event listener from an element
css(): Gets or sets the style attribute value of an element
attr() Gets or sets any attribute of an element
val(): Gets or sets the value attribute of an element
text(): Gets the combined text of an element and its children
each(): Iterates over a set of matched elements
In this article, I have provided list of most commonly used jQuery functions.
List of jQuery functions:
1. jQuery Selectors:
//--- COMMON JQUERY SELECTORS ---//
// get element by id
$("#ElementID").whatever();
// get element by css class
$(".ClassName").whatever();
// get elements where id contains a string
$("[id*='value']").whatever();
// get elements where id starts with a string
$("[id^='value']").whatever();
// get elements where id ends with a string
$("[id$='value']").whatever();
// get all elements of certain type (can use "p", "a", "div" - any html tag)
$("div").whatever();
2. jQuery Toggle, Show and Hide Functions:
//--- JQUERY TOGGLE/SHOW/HIDE ---//
// toggle hide/show of an element
$("#DivID").toggle(1000);
// do something when animation is complete
$("#DivID").toggle(1000, function () {
alert("Toggle Complete");
});
// hide an element
$("#DivID").hide(1000);
// do something when animation is complete
$("#DivID").hide(1000, function () {
alert("Hide Complete");
});
// show an element
$("#DivID").show(1000);
// do something when animation is complete
$("#DivID").show(1000, function () {
alert("Show Complete");
});
3. jQuery Slide Functions:
//--- JQUERY SLIDE - SLIDE AN ELEMENT IN AND OUT ---//
// toggle slide up and down
$("#DivID").slideToggle(1000);
// do something when animation complete
$("#DivID").slideToggle(1000, function () {
alert("Slide Toggle Complete");
});
// slide up
$("#DivID").slideUp(1000);
// do something when animation is complete
$("#DivID").slideUp(1000, function () {
alert("Slide Up Complete");
});
// slide down
$("#DivID").slideDown(1000);
// do something when animation is complete
$("#DivID").slideDown(1000, function () {
alert("Slide Down Complete");
});
4. jQuery Fade Functions:
//--- JQUERY FADE - FADE AN ELEMENT IN, OUT & TO ---//
// fade in
$("#DivID").fadeIn(1000);
// do something when animation complete
$("#DivID").fadeIn(1000, function () {
alert("Fade In Complete");
});
// fade out
$("#DivID").fadeOut(1000);
// do something when animation is complete
$("#DivID").fadeOut(1000, function () {
alert("Fade Out Complete");
});
// fade to (fades to specified opacity)
$("#DivID").fadeTo(1000, 0.25);
// do something when animation is complete
$("#DivID").fadeTo(1000, 0.25, function () {
alert("Fade To Complete");
});
5. jQuery Animate Functions:
//--- ANIMATE (EXAMPLE USES OPACITY, BUT CAN USE ANY CSS PROPERTY. ---//
//--- NOTE SOME MY REQUIRE THE USE OF A PLUGIN SUCH AS JQUERY COLOR ANIMATION PLUGIN. ---//
$("#DivID").animate({ opacity: 0.25 }, 1000);
// do something when animation complete
$("#DivID").animate({ opacity: 0.25 }, 1000, function () {
alert("Opacity Animation Complete");
});
6. Add & Remove CSS Classes:
//--- ADD & REMOVE CSS CLASSES ---///
// add css class
$("#DivID").addClass("newclassname");
// remove css class
$("#DivID").removeClass("classname");
// add & remove class together
$("#DivID").removeClass("classname").addClass("newclassname");
// add & remove multiple classes
$("#DivID").removeClass("classname classname2").addClass("newclassname newclassname2");
7. Get & Set Textbox Values:
//--- GET & SET TEXTBOX VALUE ---//
//--- CAN ALSO BE USED ON ANY OTHER ELEMENT THAT HAS A VALUE PROPERTY ---//
// get the value of a textbox
var TextboxValue = $("#TextboxID").val();
// set the value of a textbox
$("#TextboxID").val("New Textbox Value Here");
8. Get & Set Element's HTML:
//--- GET & SET HTML OF ELEMENT ---//
// get element html
var DivHTML = $("#DivID").html();
// set element html
$("#DivID").html("This is the new html
");
9. Get & Set Element's Text:
//--- GET & SET TEXT OF ELEMENT ---//
// get text of element
var DivText = $("#DivID").text();
// set text of element
$("#DivID").text("This is the new text.");
10. Get & Set Element's Width & Height:
//--- GET & SET ELEMENT'S WIDTH & HEIGHT
// get element height
var ElementHeight = $("#DivID").height();
// set element height
$("#DivID").height(300);
// get element width
var ElementWidth = $("#DivID").width();
// set element width
$("#DivID").width(600);
11. EXTRA: Change Element's CSS Property
//--- CHANGE AN ELEMENT'S CSS PROPERTY ---//
$("#DivID").css("background-color", "#000");
$("#DivID").css("border", "solid 2px #ff0000");
12. each() jQuery API function:
$("#DivID").each(function(index, value) {
console.log('DivID' + index + ':' + $(this).attr('id'));
});
Here is the list of most commonly used jQuery API functions:
find(): Selects elements based on the provided selector string
hide(): Hides an element if it was visible
show(): Shows an element if it was hidden
html(): Gets or sets an inner HTML of an element
append() Injects an element into the DOM after the selected element
prepend() Injects an element into the DOM before the selected element
on(): Attaches an event listener to an element
off() Detaches an event listener from an element
css(): Gets or sets the style attribute value of an element
attr() Gets or sets any attribute of an element
val(): Gets or sets the value attribute of an element
text(): Gets the combined text of an element and its children
each(): Iterates over a set of matched elements
Yahoo Weather API PHP Script Example/Widget
Posted by Raj
Yahoo Weather API PHP Script Example/Widget
In this example, I will show how to create weather application using Yahoo Weather API.Yahoo Weather API allows developers and programmers to get up-to-date weather information for your location.Yahoo Weather API provides local & long range Weather Forecast, Current Conditions, weather icons and two day future.
OUTPUT:
I hope above example will help you to get weather Information for your location.
For more details check : http://developer.yahoo.com/weather
In this example, I will show how to create weather application using Yahoo Weather API.Yahoo Weather API allows developers and programmers to get up-to-date weather information for your location.Yahoo Weather API provides local & long range Weather Forecast, Current Conditions, weather icons and two day future.
<?php
/*
Example: Yahoo! Weather API Example Using SimpleXML in PHP.
The base URL for the Weather RSS feed is
http://weather.yahooapis.com/forecastrss
Parameters
w WOEID
e.g: w=111111
u Units for temperature
f: Fahrenheit
c: Celsius
e.g.: u=c
*/
$city="bangalore";
$result1 = file_get_contents("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20text%3D%22$city%22&format=xml");
$xml1 = simplexml_load_string($result1);
$woeid=$xml1->results->place->woeid;
if($woeid!="")
{
$fetchData = file_get_contents("http://weather.yahooapis.com/forecastrss?w=$woeid&u=c");
$xmlData = simplexml_load_string($fetchData);
$location = $xmlData->channel->xpath('yweather:location');
if(!empty($location))
{
foreach($xmlData->channel->item as $data)
{
$current_condition = $data->xpath('yweather:condition');
$forecast = $data->xpath('yweather:forecast');
$current_condition = $current_condition[0];
echo "
<table width=40% border=1 align=center>
<tr>
<td align=center style='background-color:yellow'>
<h1>{$location[0]['city']}, {$location[0]['region']}</h1>
<small>Date: {$current_condition['date']}</small>
<h2>Current Temprature</h2>
<p>
<span style=\"font-size:64px;font-color:red; font-weight:bold;\">{$current_condition['temp']}°C</span>
<br/>
<img src=\"http://l.yimg.com/a/i/us/we/52/{$current_condition['code']}.gif\" style=\"vertical-align: middle;\"/>
{$current_condition['text']}
</p>
<h2>Forecast</h2>
<b>{$forecast[0]['day']}</b> : {$forecast[0]['text']}. <b>High:</b> {$forecast[0]['high']} <b>Low:</b> {$forecast[0]['low']}
<br/>
<b>{$forecast[1]['day']}</b> - {$forecast[1]['text']}. <b>High:</b> {$forecast[1]['high']} <b>Low:</b> {$forecast[1]['low']}
</p>
</td>
</tr></table>
";
}
}
else
{
echo "<h1>please try a different City.</h1>";
}
}
else
{
echo "<h1>Please try a different City.</h1>";
}
?>
OUTPUT:
I hope above example will help you to get weather Information for your location.
For more details check : http://developer.yahoo.com/weather
Create Dynamic Bar Graph/Chart in php
Posted by Raj
Create Dynamic Bar Graph/Chart in php
In this article, I will show how to dynamically create bar graph in PHP. I have created PHP script to create a bar graph in php such that x-scale and y-scale changes dynamically.
Example : Create dynamic Graph/Chart image page using MySQL&PHP
I hope this example will help you to create Dynamic Bar Graph/Chart in php.
In this article, I will show how to dynamically create bar graph in PHP. I have created PHP script to create a bar graph in php such that x-scale and y-scale changes dynamically.
Example : Create dynamic Graph/Chart image page using MySQL&PHP
<?php
$hrs= array( "0" => 11, "1" => 12 ,"2" => 13 ,"3" => 14 ,"4" => 15);
$data= array ("0" => 15 ,"1" => 11, "2" => 5, "3" => 15 ,"4" => 17 );
$hrs_len=sizeof($hrs);
if(!empty($data) && !empty($hrs))
{
$data=array_combine($hrs,$data);
$image_width=($hrs_len+1)*32;
$image_height=80;
$padding=20;
$graph_width=$image_width - $padding * 2;
$graph_height=$image_height - $padding * 2;
$image=imagecreate($image_width,$image_height);
$bar_width=25;
$total_bars=count($data);
$gap= 5;
$background_color=imagecolorallocate($image,255,255,255);
$border_color=imagecolorallocate($image,255,255,255);
$line_color=imagecolorallocate($image,255,255,255);
$max_value=max($data);
$ratio= $graph_height/$max_value;
$horizontal_data=20;
$horizontal_gap=$graph_height/$horizontal_data;
for($i=1;$i<=$horizontal_data;$i++){
$y=$image_height - $padding - $horizontal_gap * $i ;
imageline($image,$padding,$y,$image_width-$padding,$y,$line_color);
$v=intval($horizontal_gap * $i /$ratio);
}
$bar_color=imagecolorallocate($image,50,205,50);
for($i=0;$i< $total_bars; $i++){
list($key,$value)=each($data);
$x1= $padding + $gap + $i * ($gap+$bar_width) ;
$x2= $x1 + $bar_width;
$y1=$padding +$graph_height- intval($value * $ratio) ;
$y2=$image_height-$padding;
imagestring($image,0,$x1+3,$y1-10,$value,$bar_color);
imagestring($image,0,$x1+3,$image_height-15,$key,$bar_color);
imagefilledrectangle($image,$x1,$y1,$x2,$y2,$bar_color);
}
header("Content-type:image/png");
imagepng($image);
}
?>
I hope this example will help you to create Dynamic Bar Graph/Chart in php.
HTML5 interview questions and Answers - HTML5 Quiz.
Posted by Raj
HTML5 interview questions and Answers - HTML5 Quiz.
In this section, I have selected advanced HTML5 interview questions and answers for Fresher and experienced cadidates. Last few months I have been working to select best HTML5 Job interview question and answer set for IT interview questions.
HTML5 interview questions and Answers:
What is HTML5?
Ans : HTML5 is The New HTML Standard with new elements, attributes, and behaviors.
----------------------------------------------------------------------------------------------
HTML 5 Features:
Ans :
What is HTML5 Web Storage?
Ans : In HTML5, we can store data locally within the user's browser.It is possible to store large amounts of data without affecting the website’s performance.
Web Storage is more secure and faster.
there are two types of Web Storages
1.LocalStorage:stores data locally with no limit
2.SessionStorage:stores data for one session
----------------------------------------------------------------------------------------------
How to store data on client in HTML5?
Ans : we can store data using HTML5 Web Storage.
1.LocalStorage
<script type="text/javascript">
localStorage.name="Raj";
document.write(localStorage.name);
</script>
2.SessionStorage
<script type="text/javascript">
sessionStorage.email="test@gmail.com";
document.write(sessionStorage.email);
</script>
----------------------------------------------------------------------------------------------
How do you play a Video using HTML5?
Ans : HTML5 defines a new element to embed a video on Web Page
the <video> element.
Example:
<video width="500" height="300" controls>
<source src="video1.mp4" type="video/mp4">
</video>
----------------------------------------------------------------------------------------------
How do you play a Audio using HTML5?
Ans : HTML5 defines a new element to embed a video on Web Page
the <audio> element.
Example:
<audio controls>
<source src="audio.mp3" type="audio/mpeg">
</audio>
----------------------------------------------------------------------------------------------
Canvas Element in HTML5?
Ans : The canvas element is used to draw graphics images on a web page
<canvas id="canvas_image" width="400" height="200"></canvas>
The canvas is a two-dimensional grid.
----------------------------------------------------------------------------------------------
HTML5 <input> Types ?
Ans :
----------------------------------------------------------------------------------------------
HTML5 New Form Attributes?
Ans :
What does a <hgroup> tag do?
Ans : The <hgroup> tag is used to group heading elements.
The <hgroup> element is used to group a set of <h1> to <h6> elements.
<hgroup>
<h1>Hello</h1>
<h2>How r u?</h2>
</hgroup>
----------------------------------------------------------------------------------------------
Which video formats are used for the video element?
Ans :
Internet Explorer 9+: MP4
Chrome 6+: MP4, WebM, Ogg
Firefox 3.6+ : WebM, Ogg
Safari 5+ : MP4,
Opera 10.6+ : WebM,Ogg
----------------------------------------------------------------------------------------------
Difference between HTML4 and HTML5
----------------------------------------------------------------------------------------------
What is the <!DOCTYPE> ? Is it necessary to use in HTML5 ?
Ans : The <!DOCTYPE> declaration must be the very first thing in HTML5 document, before the <html> tag
----------------------------------------------------------------------------------------------
What are the New Media Elements in HTML5?
Ans :
In this section, I have selected advanced HTML5 interview questions and answers for Fresher and experienced cadidates. Last few months I have been working to select best HTML5 Job interview question and answer set for IT interview questions.
HTML5 interview questions and Answers:
What is HTML5?
Ans : HTML5 is The New HTML Standard with new elements, attributes, and behaviors.
----------------------------------------------------------------------------------------------
HTML 5 Features:
Ans :
- The <canvas> element for 2D drawing
- The <video> and <audio> elements for media playback
- local storage support.
- Added New elements, like <figure>,<small>, <header>, <nav>,<article>, <footer>, <section>,<mark>
- New form controls, like placeholder,calendar, date, time, email, url, search,required ,autofocus
- In HTML5 there is only one <!doctype> declaration: <!DOCTYPE html>
What is HTML5 Web Storage?
Ans : In HTML5, we can store data locally within the user's browser.It is possible to store large amounts of data without affecting the website’s performance.
Web Storage is more secure and faster.
there are two types of Web Storages
1.LocalStorage:stores data locally with no limit
2.SessionStorage:stores data for one session
----------------------------------------------------------------------------------------------
How to store data on client in HTML5?
Ans : we can store data using HTML5 Web Storage.
1.LocalStorage
<script type="text/javascript">
localStorage.name="Raj";
document.write(localStorage.name);
</script>
2.SessionStorage
<script type="text/javascript">
sessionStorage.email="test@gmail.com";
document.write(sessionStorage.email);
</script>
----------------------------------------------------------------------------------------------
How do you play a Video using HTML5?
Ans : HTML5 defines a new element to embed a video on Web Page
the <video> element.
Example:
<video width="500" height="300" controls>
<source src="video1.mp4" type="video/mp4">
</video>
----------------------------------------------------------------------------------------------
How do you play a Audio using HTML5?
Ans : HTML5 defines a new element to embed a video on Web Page
the <audio> element.
Example:
<audio controls>
<source src="audio.mp3" type="audio/mpeg">
</audio>
----------------------------------------------------------------------------------------------
Canvas Element in HTML5?
Ans : The canvas element is used to draw graphics images on a web page
<canvas id="canvas_image" width="400" height="200"></canvas>
The canvas is a two-dimensional grid.
----------------------------------------------------------------------------------------------
HTML5 <input> Types ?
Ans :
- search
- tel
- time
- color
- month
- date
- datetime
- datetime-local
- number
- range
- url
- week
----------------------------------------------------------------------------------------------
HTML5 New Form Attributes?
Ans :
- pattern
- placeholder
- required
- step
- autocomplete
- autofocus
- height and width
- list
- min and max
- multiple
- form
- formaction
- formenctype
- formmethod
- formnovalidate
- formtarget
What does a <hgroup> tag do?
Ans : The <hgroup> tag is used to group heading elements.
The <hgroup> element is used to group a set of <h1> to <h6> elements.
<hgroup>
<h1>Hello</h1>
<h2>How r u?</h2>
</hgroup>
----------------------------------------------------------------------------------------------
Which video formats are used for the video element?
Ans :
Internet Explorer 9+: MP4
Chrome 6+: MP4, WebM, Ogg
Firefox 3.6+ : WebM, Ogg
Safari 5+ : MP4,
Opera 10.6+ : WebM,Ogg
----------------------------------------------------------------------------------------------
Difference between HTML4 and HTML5
----------------------------------------------------------------------------------------------
What is the <!DOCTYPE> ? Is it necessary to use in HTML5 ?
Ans : The <!DOCTYPE> declaration must be the very first thing in HTML5 document, before the <html> tag
----------------------------------------------------------------------------------------------
What are the New Media Elements in HTML5?
Ans :
- <audio>
- <video>
- <source>
- <embed>
- <track>
Post data to a specific port using PHP/Curl.
Posted by Raj
Post data to a specific port using PHP/Curl.
In this article,I will show how to Post data to a specific port using PHP/Curl Method. PHP-curl library can be used to communicate with a specific port under Linux and windows platform.
Example: Send data to Port in PHP.
In this article,I will show how to Post data to a specific port using PHP/Curl Method. PHP-curl library can be used to communicate with a specific port under Linux and windows platform.
Example: Send data to Port in PHP.
<?php
ini_set("display_errors",1);
error_reporting(E_ERROR);
$msg="&command=1";
$url = "http://127.0.0.1:1234";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $msg);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
if($response!="")
{
$fp = fopen("test.txt","w");
fwrite( $fp, $response);
fclose($fp);
}
curl_close($curl);
?>
Apache Interview Questions and Answers - Apache Web Server
Posted by Raj
Apache Interview Questions and Answers - Apache Web Server
In this section, I have selected Basic and Important Apache interview questions and answers for all levels of candidates(Fresher level, experienced level).Last few months I have been working to select best question and answer set for Apache interview questions.
Apache Interview Questions and Answers:
------------------------------------------------------------------------------------------------------------
How do you set up a virtual host in Apache?
Ans: <VirtualHost www.test.com>
ServerAdmin admin@test.com
DocumentRoot /home/Public_html/site
ServerName www.test.com
ErrorLog /home/apache/logs/error/site/error_log
TransferLog /home/apache/logs/access/site/access_log
</VirtualHost>
------------------------------------------------------------------------------------------------------------
In this section, I have selected Basic and Important Apache interview questions and answers for all levels of candidates(Fresher level, experienced level).Last few months I have been working to select best question and answer set for Apache interview questions.
Apache Interview Questions and Answers:
------------------------------------------------------------------------------------------------------------
How do you set up a virtual host in Apache?
Ans: <VirtualHost www.test.com>
ServerAdmin admin@test.com
DocumentRoot /home/Public_html/site
ServerName www.test.com
ErrorLog /home/apache/logs/error/site/error_log
TransferLog /home/apache/logs/access/site/access_log
</VirtualHost>
------------------------------------------------------------------------------------------------------------
htpasswd :
Ans: It creates a new user and asks to specify a password for that user.
------------------------------------------------------------------------------------------------------------
What's the command to stop Apache?
Ans:
apachectl -k stop
/etc/init.d/apache2 stop (Linux)
------------------------------------------------------------------------------------------------------------
What's the command to Restart Apache?
Ans:
apachectl -k restart
/etc/init.d/apache2 restart
------------------------------------------------------------------------------------------------------------
What's the location of log files for Apache server ?
Ans: /var/log/httpd
------------------------------------------------------------------------------------------------------------
What's the Comamnd to check the version of Apache server ?
Ans: rpm -qa |grep httpd
------------------------------------------------------------------------------------------------------------
Apache server works on which ports ?
Ans: http – port 80
https – port 443
------------------------------------------------------------------------------------------------------------
Ans: If you have mod_php installed, use AddHandler.
AddHandler application/x-httpd-php .phtml .php
------------------------------------------------------------------------------------------------------------
If you specify both deny from all and allow from all, what will be the default action of Apache?
Ans: Deny always takes precedence over allow.
------------------------------------------------------------------------------------------------------------
How do you change the default web root?
Ans: Change the DocumentRoot in httpd.conf file.
------------------------------------------------------------------------------------------------------------
How to enable htaccess on Apache?
Ans:
Open httpd.conf and remove the comment on line from
;LoadModule rewrite_module modules/mod_rewrite.so
Find the following
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
and change it to
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
allow from all
------------------------------------------------------------------------------------------------------------
Does Apache act as Proxy server?
Ans: Yes,using mod_proxy module.
------------------------------------------------------------------------------------------------------------
Print a web page using PHP/JavaScript Code
Posted by Raj
Print a web page using PHP/JavaScript Code
In this article I will show how to Print a HTML Web Page using PHP/JavaScript.I have Written simple script to print Visitor card in PHP.On web page, there is a print option. When the user click on `print` Button it will send a print command to the printer.
We are using Javascript window.print(); function to print HTML portion of a Web Page.
Javascript window.print():
The window.print() method prints the contents of the current page.This method is supported in all major browsers.
Example: How to Print a Web Page Using JavaScript and PHP.
In this article I will show how to Print a HTML Web Page using PHP/JavaScript.I have Written simple script to print Visitor card in PHP.On web page, there is a print option. When the user click on `print` Button it will send a print command to the printer.
We are using Javascript window.print(); function to print HTML portion of a Web Page.
Javascript window.print():
The window.print() method prints the contents of the current page.This method is supported in all major browsers.
Example: How to Print a Web Page Using JavaScript and PHP.
<!DOCTYPE html>
<HTML lang="en"><HEAD>
<TITLE>Print Visitor card using PHP/JavaScript </TITLE>
<META content=IE=7 http-equiv=X-UA-Compatible>
<META content="text/html; charset=Windows-1252" http-equiv=Content-Type>
<STYLE>
#outer
{
border-collapse:collapse;
border: 0px solid black;
height:250px;width:420px;
}
.cover{
background:#EEEEEE;
padding: 10px;
text-align:left;
margin:10px;
width:400px;
height:200px;
font-size: 1.0em;
top:10%; left:10%;
/*--CSS3 Box Shadows--*/
-webkit-box-shadow: 0px 0px 20px #000;
-moz-box-shadow: 0px 0px 20px #000;
box-shadow: 0px 0px 20px #000;
/*--CSS3 Rounded Corners--*/
-webkit-border-radius: 30px;
-moz-border-radius: 30px;
border-radius: 30px;
}
#inner
{
border-collapse:collapse;
border: 0px solid black;
height:100%;width:100%;
background:#EEEEEE;
}
#hgt_abv
{ height:18%;}
#hgt_abv_back
{ float:inherit;
height:18px;
width:400px;
background:#000000;
}
#hgt_belo
{ height:3%;background:#FF6600;}
.docimg
{
float:inherit;
hight:119px;
width:90px;
}
.logo
{
float:left;
width:100px;
}
.address
{
padding:2px;
text-align:left;
margin:2px;
hight:100px;
width:130px;
font-size: 1.1em;
}
</STYLE>
<META name=GENERATOR content="MSHTML 9.00.8112.16446"></HEAD>
<BODY class="ExtravaganzaAqua page-view2" >
<CENTER><SPAN></SPAN>
<TABLE id=outer>
<TR>
<TD><DIV class=cover>
<TABLE id=inner border=0>
<TR>
<TD align=center colspan="2">
<DIV id=hgt_abv_back><FONT color=#ffffff size=3><B>VISITOR PASS</B></FONT></DIV>
</TD>
</TR>
<TR>
<TD valign="top" align=left><br /><FONT size=2><B>Name: </B><B>Computer Geek</B><br /><br /><br />
<B>Designation: </B><B>Software Engg.</B><br /><br /><br />
<B>Date: </B><B>24th Nov 2012</B><br />
</FONT>
</TD>
<TD valign="top" align=right>
<img width="90" hight="119px" src="user.jpg" alt="bg">
</TD>
</TR>
<TR id=hgt_belo>
<TD colSpan=2></TD>
</TR>
</TABLE>
</DIV>
</TD>
</TR>
</TABLE>
</CENTER>
<center>
<table id=outer>
<tr>
<td align="right" valign="top">
<button type="button" onclick="window.print();" >Print</button>
</td>
</tr>
</table>
</center>
</BODY>
</HTML>
I hope this example will help you to Print a Web Page Using JavaScript and PHP.
C Interview Questions and Answers For Freshers/ Experienced
Posted by Raj
C Interview Questions and Answers For Freshers / Experienced - Important Quiz
In this section, I have selected Basic and Important C interview questions and answers for all levels of candidates(Fresher level, advanced level,experienced level).
Last few months I have been working to select best question and answer set for C interview questions.
Here is some Important C Interview Questions and Answers for freshers and experienced:
1.Can we have a pointer to a pointer in C?
Answer: Yes
char *a; - Pointer to a character
char **a; - Pointer to a pointer
2.How to convert strings in c to corresponding Integer?
Answer:
atoi() function convert a string into corresponding integer value.use stdlib.h header file.
3. C Data types?
Answer :Int, char, float, void etc. are predefined basic primitive data types.Structures and Unions are user defined data types.
4.Find the output of the following program?
#include
main()
{
int i=10;
printf("%d",++i);
printf("%d",i++);
printf("%d",(i++*i++))
}
5.Octal literal in C?
#include
main()
{
int i=020;
printf("i is %d",i);
}
Output:16
Answer :
In c and c ++ language 0 (zero) is the octel literal so it will print its Octel representation of 16.
6.Whats is difference between file descriptor and file pointer?
7.Two forms of #include directive?
Answer :
1.#include”filename”
2.#include
8.Find the output of the following program?
#include
main()
{
int str=0;
if(str==0)
printf("True");
printf("False");
}
Answer :
True
False
9.Find the output of the following program?
#include
main()
{
int x=0;
if(x==0)
printf("True");
else
printf("False");
}
Answer :
True
10.What will be the Output of the following program?
#include
main()
{
int i=50, j=100;
i = j++;
j = ++j;
printf("%d %dn",i,j);
}
Answer :
51, 101
11.What will be the Output of the following program?
#include
main()
{
int i = 10;
printf("%d", main||i);
}
Answer :
1
12. Write a Program to convert decimal to binary number?
Answer :
#include
main()
{
int x,y,n,arr[50];
clrscr();
printf("Enter the decimal number");
scanf("%d",n);
for(x=0;x
{
arr[x]=n%2;
n=n/2;
}
for(y=n;y>0;y--)
{
printf("%d",arr[y]);
}
getch();
}
In this section, I have selected Basic and Important C interview questions and answers for all levels of candidates(Fresher level, advanced level,experienced level).
Last few months I have been working to select best question and answer set for C interview questions.
Here is some Important C Interview Questions and Answers for freshers and experienced:
1.Can we have a pointer to a pointer in C?
Answer: Yes
char *a; - Pointer to a character
char **a; - Pointer to a pointer
2.How to convert strings in c to corresponding Integer?
Answer:
atoi() function convert a string into corresponding integer value.use stdlib.h header file.
3. C Data types?
Answer :Int, char, float, void etc. are predefined basic primitive data types.Structures and Unions are user defined data types.
4.Find the output of the following program?
#include
main()
{
int i=10;
printf("%d",++i);
printf("%d",i++);
printf("%d",(i++*i++))
}
5.Octal literal in C?
#include
main()
{
int i=020;
printf("i is %d",i);
}
Output:16
Answer :
In c and c ++ language 0 (zero) is the octel literal so it will print its Octel representation of 16.
6.Whats is difference between file descriptor and file pointer?
7.Two forms of #include directive?
Answer :
1.#include”filename”
2.#include
8.Find the output of the following program?
#include
main()
{
int str=0;
if(str==0)
printf("True");
printf("False");
}
Answer :
True
False
9.Find the output of the following program?
#include
main()
{
int x=0;
if(x==0)
printf("True");
else
printf("False");
}
Answer :
True
10.What will be the Output of the following program?
#include
main()
{
int i=50, j=100;
i = j++;
j = ++j;
printf("%d %dn",i,j);
}
Answer :
51, 101
11.What will be the Output of the following program?
#include
main()
{
int i = 10;
printf("%d", main||i);
}
Answer :
1
12. Write a Program to convert decimal to binary number?
Answer :
#include
main()
{
int x,y,n,arr[50];
clrscr();
printf("Enter the decimal number");
scanf("%d",n);
for(x=0;x
{
arr[x]=n%2;
n=n/2;
}
for(y=n;y>0;y--)
{
printf("%d",arr[y]);
}
getch();
}
Top Important C FAQs and Interview Questions
- What is the difference between strings and character arrays?
- Differences between pass by reference and pass by value?
- What does static variable mean?
- What is the use of semicolon at the end of every statement?
- What is a null pointer?
- What is a pointer?
- When would you use a pointer to a function?
- What are the uses of a pointer?
- In header files whether functions are declared or defined?
- What are the differences between malloc () and calloc ()?
- What is the heap?
- What is the stack?
- Difference between const char* p and char const* p?
- What is a structure?
- What is a union?
- What is Operator overloading ?
- What is a void pointer?
- What is hashing?
- What are the different storage classes in C?
- What are the differences between structures and union?
- What is the difference between calloc() and malloc()?
- What are the differences between structures and arrays?
- What is the difference between printf() and sprintf()?
- What is static memory allocation and dynamic memory allocation?
- Define recursion in C?
- What is the use of typedef?
- How are pointer variables initialized?
- What are the advantages of auto variables?
C Program to find smallest number with Output in a given array of elements.
Posted by Raj
C Program to find smallest number with Output in a given array of elements.
In this article ,I have written simple c program to find smallest number in a given array of elements.
Interview Question : Write a program to find the smallest and largest element in a given array in c?
Example:
/***
Program to find smallest Number
***/
#include<stdio.h>
#include<conio.h>
main()
{
int arr[50],n,j,s;
clrscr();
printf("Enter the size of array:");
scanf("%d",&n);
printf("Enter %d integers:",n);
for(j=0;j
scanf("%d",&arr[i]);
s==arr[0];
for(j=0;j
{
if(arr[i]
s=arr[i];
}
printf("Smallest number is %d",s);
getch();
}
Output:
Enter the size of array:3
34
35
60
Smallest number is: 34
How to enable SSl on Wamp Server(apache2) - HTTPS Configuration
Posted by Raj
How to enable SSl on Wamp Server(apache2) - HTTPS Configuration
In this article, I will show how to Configure/Enable SSL in Wamp Server.I have installed wampserver with apache 2.2.12 and php 5.3.5. I have to configure the Open SSL server.
1. Install WAMPServer
2. Open Control Panel
3. Click System >> Select Advanced System Setting >> Select Environment Variables.
4.Create new system variable OPENSSL_CONF:
Value: C:\wamp\bin\apache\apache2.2.12\conf\openssl.cnf
5. Create a SSL Certificate and Key for the Web Server
Open command prompt and Run the following commands:
>cd wamp\bin\apache\apache2.2.12\bin
>openssl genrsa -des3 -out server.key 1024
>copy server.key server.key.org
>openssl rsa -in server.key.org -out server.key
>openssl req -new -x509 -nodes -sha1 -days 365 -key server.key -out server.crt -config C:\wamp\bin\apache\apache2.2.12\conf\openssl.cnf
Create a folder c:\wamp\OpenSSL with the following subfolders:
i. certificats
ii. private
Copy server.cert, server.csr, server.key files
from C:\wamp\bin\apache\Apache2.2.12\bin to C:\wamp\OpenSSL\certificats folder
Copy server.key.org file from
C:\wamp\bin\apache\Apache2.2.12\bin to C:\wamp\OpenSSL\private folder
6. Open Php.ini file
Remove comment of following line:
extension=php_openssl.dll
OR
Left click the wampserver icon >> PHP >> php extensions >> click php_openssl
7. Open Httpd.conf file (C:\wamp\bin\apache\Apache2.2.12\conf\)
Remove comment of following lines:
LoadModule ssl_module modules/mod_ssl.so
LoadModule setenvif_module modules/mod_setenvif.so
Include conf/extra/httpd_ssl.conf
8.Open httpd-ssl.conf file(C:\wamp\bin\apache\Apache2.2.12\conf\extra\)
Find and replace follwing lines:
SSLMutex default
DocumentRoot "C:/wamp/www"
ErrorLog "C:/wamp/logs/ssl_ErrorLog.txt"
TransferLog "C:/wamp/logs/ssl_TransferLog.txt"
SSLCertificateFile "C:/wamp/OpenSSL/certificats/server.crt"
SSLCertificateKeyFile "C:/wamp/OpenSSL/certificats/server.key"
CustomLog "C:/wamp/logs/ssl_request.txt" \
"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
Change Directory Tag:
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
9.Verify SSL/HTTPS
10.Check whether the WAMP server is running or not
Right click the wampserver icon >> Rsstart All Services
11.Open https://localhost
12.Done.
I hope this article will help you to enable SSL on the Apache server.
In this article, I will show how to Configure/Enable SSL in Wamp Server.I have installed wampserver with apache 2.2.12 and php 5.3.5. I have to configure the Open SSL server.
How to Setup HTTPS SSL on WAMP Server for apache 2.2
1. Install WAMPServer
2. Open Control Panel
3. Click System >> Select Advanced System Setting >> Select Environment Variables.
4.Create new system variable OPENSSL_CONF:
Value: C:\wamp\bin\apache\apache2.2.12\conf\openssl.cnf
5. Create a SSL Certificate and Key for the Web Server
Open command prompt and Run the following commands:
>cd wamp\bin\apache\apache2.2.12\bin
>openssl genrsa -des3 -out server.key 1024
>copy server.key server.key.org
>openssl rsa -in server.key.org -out server.key
>openssl req -new -x509 -nodes -sha1 -days 365 -key server.key -out server.crt -config C:\wamp\bin\apache\apache2.2.12\conf\openssl.cnf
Create a folder c:\wamp\OpenSSL with the following subfolders:
i. certificats
ii. private
Copy server.cert, server.csr, server.key files
from C:\wamp\bin\apache\Apache2.2.12\bin to C:\wamp\OpenSSL\certificats folder
Copy server.key.org file from
C:\wamp\bin\apache\Apache2.2.12\bin to C:\wamp\OpenSSL\private folder
6. Open Php.ini file
Remove comment of following line:
extension=php_openssl.dll
OR
Left click the wampserver icon >> PHP >> php extensions >> click php_openssl
7. Open Httpd.conf file (C:\wamp\bin\apache\Apache2.2.12\conf\)
Remove comment of following lines:
LoadModule ssl_module modules/mod_ssl.so
LoadModule setenvif_module modules/mod_setenvif.so
Include conf/extra/httpd_ssl.conf
8.Open httpd-ssl.conf file(C:\wamp\bin\apache\Apache2.2.12\conf\extra\)
Find and replace follwing lines:
SSLMutex default
DocumentRoot "C:/wamp/www"
ErrorLog "C:/wamp/logs/ssl_ErrorLog.txt"
TransferLog "C:/wamp/logs/ssl_TransferLog.txt"
SSLCertificateFile "C:/wamp/OpenSSL/certificats/server.crt"
SSLCertificateKeyFile "C:/wamp/OpenSSL/certificats/server.key"
CustomLog "C:/wamp/logs/ssl_request.txt" \
"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
Change Directory Tag:
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
9.Verify SSL/HTTPS
- Run httpd –t and make sure the syntax is OK.
- Restart Apache.
10.Check whether the WAMP server is running or not
Right click the wampserver icon >> Rsstart All Services
- If icon is partially red, it means no service is currently running
- If icon is White, that means all services are running.
11.Open https://localhost
12.Done.
I hope this article will help you to enable SSL on the Apache server.
JQuery Dialog Box Auto Close Event after 5 seconds - Example
Posted by Raj
JQuery Dialog Box Close Event Example
In this article,I will show how to Open/destroy/auto close dialog box after x seconds. jQuery Dialog Close event gives you a very simple way to close a jQuery UI dialog box after x seconds.I have written JavaScript code to Open and Close dialog box after a certaing amount of seconds.
Example:Auto Close jQuery UI Dialog Box
<!doctype html>
<html lang="en">
<head>
<title>Auto Close JQuery Dialog Box Example</title>
<style>
</style>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<script>
$(function() {
$( "#dialog_box" ).dialog({
modal: true,
width:400});
});
setInterval(function(){AutoClose()},5000);//JQuery UI Dialog box will auto close after 5 seconds.
function AutoClose()
{
$(function() {
$( "#dialog_box" ).dialog( "close" );// //Auto Close Dialog Box.
});
}
</script>
</head>
<body0>
<div id="dialog_box" title="JQuery Dialog Box Example">
<p>Alert Message for displaying information</p>
</div>
</body>
</html>
I hope this example will help you to Close JQuery UI dialog box after 5 seconds.
In this article,I will show how to Open/destroy/auto close dialog box after x seconds. jQuery Dialog Close event gives you a very simple way to close a jQuery UI dialog box after x seconds.I have written JavaScript code to Open and Close dialog box after a certaing amount of seconds.
Example:Auto Close jQuery UI Dialog Box
<!doctype html>
<html lang="en">
<head>
<title>Auto Close JQuery Dialog Box Example</title>
<style>
</style>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<script>
$(function() {
$( "#dialog_box" ).dialog({
modal: true,
width:400});
});
setInterval(function(){AutoClose()},5000);//JQuery UI Dialog box will auto close after 5 seconds.
function AutoClose()
{
$(function() {
$( "#dialog_box" ).dialog( "close" );// //Auto Close Dialog Box.
});
}
</script>
</head>
<body0>
<div id="dialog_box" title="JQuery Dialog Box Example">
<p>Alert Message for displaying information</p>
</div>
</body>
</html>
I hope this example will help you to Close JQuery UI dialog box after 5 seconds.
Linkedin API Examples in PHP to get connections,email address,profile and phone number
Posted by Raj
Linkedin API Examples in PHP to get connections,email address,profile and phone number
In this Article,I have explained how to use Linkedin API using PHP Script to get all the connections,Contacts,email address,profile and phone number of linkedin users.
LinkedIn API allows users to fetch the email addresses,phone number of their LinkedIn contacts to our site.
Get Profile Info:
LinkedIn API requires the following permissions to get Connections
Permissions :r_basicprofile,r_fullprofile
Description: Required to retrieve Basic profile(Name, photo, headline, and current positions)and Full profile including experience, education, skills, and recommendations.
Get Email Address:
LinkedIn API requires the following permissions to get Email Address
Permissions :r_emailaddress
Description: Required to retrieve Email Address.
Get Connections:
LinkedIn API requires the following permissions to get Connections
Permissions: r_network
Description: Required to retrieve 1st and 2nd degree connections
1. Download Linkedin API 3.2.0.zip file from http://code.google.com/p/simple-linkedinphp.
2.You need to apply for a LinkedIn Application Key here(https://www.linkedin.com/secure/developer)to get the required API key and Secret key.
3.Demo Application Key Details:
Company:Demo
Application Name: Demo
API Key:jkbccri8fkjq
Secret Key:4NBTsJM5hTpCdFeA
OAuth User Token:d7b31d47-3c59-4eb1-8122-b1175dfa84a0
OAuth User Secret:42224c12-c8dd-4630-b2c5-bfb2560f1af1
4. Installing the Files
- Extract Zip file on Web Server.
- Download OAuth.php file from http://code.google.com/p/oauth.
5.Open Demo.php.
6.Insert your LinkedIn application key into the $API_CONFIG configuration array:
$API_CONFIG = array(
'appKey' => '',
'appSecret' => '',
'callbackUrl' => NULL
);
7.Open Linkedin class file and insert below line into the _URL_REQUEST constant Variable:
const _URL_REQUEST = 'https://api.linkedin.com/uas/oauth/requestToken?scope=r_basicprofile+r_emailaddress+r_network+r_fullprofile+r_contactinfo';
8.Open demo.php file and insert below line into the $response Variable:
$response = $OBJ_linkedin->profile('~:(id,first-name,last-name,picture-url,email-address,phone-numbers)');
9.Open demo.php in browser.
10.Done.
I hope it will help you to integrate Linkedin API in your site.
In this Article,I have explained how to use Linkedin API using PHP Script to get all the connections,Contacts,email address,profile and phone number of linkedin users.
LinkedIn API allows users to fetch the email addresses,phone number of their LinkedIn contacts to our site.
Get Profile Info:
LinkedIn API requires the following permissions to get Connections
Permissions :r_basicprofile,r_fullprofile
Description: Required to retrieve Basic profile(Name, photo, headline, and current positions)and Full profile including experience, education, skills, and recommendations.
Get Email Address:
LinkedIn API requires the following permissions to get Email Address
Permissions :r_emailaddress
Description: Required to retrieve Email Address.
Get Connections:
LinkedIn API requires the following permissions to get Connections
Permissions: r_network
Description: Required to retrieve 1st and 2nd degree connections
Steps To Integrate Linkedin API in your site
1. Download Linkedin API 3.2.0.zip file from http://code.google.com/p/simple-linkedinphp.
2.You need to apply for a LinkedIn Application Key here(https://www.linkedin.com/secure/developer)to get the required API key and Secret key.
3.Demo Application Key Details:
Company:Demo
Application Name: Demo
API Key:jkbccri8fkjq
Secret Key:4NBTsJM5hTpCdFeA
OAuth User Token:d7b31d47-3c59-4eb1-8122-b1175dfa84a0
OAuth User Secret:42224c12-c8dd-4630-b2c5-bfb2560f1af1
4. Installing the Files
- Extract Zip file on Web Server.
- Download OAuth.php file from http://code.google.com/p/oauth.
5.Open Demo.php.
6.Insert your LinkedIn application key into the $API_CONFIG configuration array:
$API_CONFIG = array(
'appKey' => '
'appSecret' => '
'callbackUrl' => NULL
);
7.Open Linkedin class file and insert below line into the _URL_REQUEST constant Variable:
const _URL_REQUEST = 'https://api.linkedin.com/uas/oauth/requestToken?scope=r_basicprofile+r_emailaddress+r_network+r_fullprofile+r_contactinfo';
8.Open demo.php file and insert below line into the $response Variable:
$response = $OBJ_linkedin->profile('~:(id,first-name,last-name,picture-url,email-address,phone-numbers)');
9.Open demo.php in browser.
10.Done.
I hope it will help you to integrate Linkedin API in your site.


