Friday, 24 July 2015

Incrementing/Decrementing Operators

Note: The increment/decrement operators only affect numbers and strings. Arrays, objects and resources are not affected. Decrementing NULL values has no effect too, but incrementing them results in 1.
Increment/decrement Operators
ExampleNameEffect
++$aPre-incrementIncrements $a by one, then returns $a.
$a++Post-incrementReturns $a, then increments $a by one.
--$aPre-decrementDecrements $a by one, then returns $a.
$a--Post-decrementReturns $a, then decrements $a by one.
Here's a simple example script:
<?phpecho "<h3>Postincrement</h3>";$a 5;
echo 
"Should be 5: " $a++ . "<br />\n";
echo 
"Should be 6: " $a "<br />\n";

echo 
"<h3>Preincrement</h3>";$a 5;
echo 
"Should be 6: " . ++$a "<br />\n";
echo 
"Should be 6: " $a "<br />\n";

echo 
"<h3>Postdecrement</h3>";$a 5;
echo 
"Should be 5: " $a-- . "<br />\n";
echo 
"Should be 4: " $a "<br />\n";

echo 
"<h3>Predecrement</h3>";$a 5;
echo 
"Should be 4: " . --$a "<br />\n";
echo 
"Should be 4: " $a "<br />\n";?>

Tuesday, 21 July 2015

Delete multiple rows from mysql with checkbox

Delete multiple rows from mysql with checkbox

Delete multiple rows from mysql with checkbox.

Syntax

"DELETE FROM table_name WHERE column_name = 'value' ";

Overview

In this tutorial create 1 file
1. delete_multiple.php 

Step
1. Create table"test_mysql" in database "test".
2. Create file delete_multiple.php.

Create table "test_mysql"


CREATE TABLE `test_mysql` (
`id` int(4) NOT NULL auto_increment,
`name` varchar(65) NOT NULL default '',
`lastname` varchar(65) NOT NULL default '',
`email` varchar(65) NOT NULL default '',
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=7 ;
-- 
-- Dumping data for table `test_mysql`
--
INSERT INTO `test_mysql` VALUES (1, 'Billly', 'Blueton', 'bb5@phpeasystep.com');
INSERT INTO `test_mysql` VALUES (2, 'Jame', 'Campbell', 'jame@somewhere.com');
INSERT INTO `test_mysql` VALUES (3, 'Mark', 'Jackson', 'mark@phpeasystep.com');
INSERT INTO `test_mysql` VALUES (4, 'Linda', 'Travor', 'lin65@phpeasystep.com');
INSERT INTO `test_mysql` VALUES (5, 'Joey', 'Ford', 'fordloi@somewhere.com');
INSERT INTO `test_mysql` VALUES (6, 'Sidney', 'Gibson', 'gibson@phpeasystep.com');

Create file delete_multiple.php

View in browser
############### Code
<?php
$host="localhost"; // Host name 
$username=""; // Mysql username 
$password=""; // Mysql password 
$db_name="test"; // Database name 
$tbl_name="test_mysql"; // Table name 

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);

$count=mysql_num_rows($result);
?>

<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td><form name="form1" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td bgcolor="#FFFFFF">&nbsp;</td>
<td colspan="4" bgcolor="#FFFFFF"><strong>Delete multiple rows in mysql</strong> </td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Name</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Lastname</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Email</strong></td>
</tr>

<?php
while($rows=mysql_fetch_array($result)){
?>


<tr>
<td align="center" bgcolor="#FFFFFF"><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['id']; ?>"></td>
<td bgcolor="#FFFFFF"><? echo $rows['id']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['name']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['lastname']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['email']; ?></td>
</tr>

<?php
}
?>


<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td>
</tr>

<?php
// Check if delete button active, start this 
if($delete){
for($i=0;$i<$count;$i++){
$del_id = $checkbox[$i];
$sql = "DELETE FROM $tbl_name WHERE id='$del_id'";
$result = mysql_query($sql);
}
// if successful redirect to delete_multiple.php 
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=delete_multiple.php\">";
}
}
mysql_close();
?>

</table>
</form>
</td>
</tr>
</table>

PHP Variable Interpolation

PHP supports interpolation of variables in between set of words to be printed to the browser using PHP output statements like echo(), print() and etc. There are two methods in variable interpolation. First method is to use variables in between string enclosed by double quotes which is shown as follows.
$name = "PHPPOT";
echo "I am reading $name"; // output: I am reading PHPPOT
Then, the variable interpolation can also be implemented with here document which contains several lines of string to be printed. PHP variables will be included to replace their value. A here document will be as follows to print the content as it is including line breaks, quotes and etc.
$myDoc = <<< EOD
I am reading PHPPOT
to know all about PHP
EOD;
echo $myDoc;
php_variable_interpolation
In another method of variable interpolation, the variables will be enclosed by curly braces to replace its value inside a word that is not separated by any white space. This can be clearly understood by the following example.
$name = "PHP";
echo "I am reading {$name}POT"; // output: I am reading PHPPOT
Here, in the above program, the variable $name is associated with the string POTwithout any white space. So that, the curly braces are needed around the variable name to distinguish both. Otherwise, execution process will look for the variable$namePOT, which is no more.

Note:

  • Among both of the above two methods, the first one is the easiest method.
  • Variable interpolation is not possible with in single quotes

PHP Data Type Conversion

In PHP, variable’s data type is taken depends on the value assigned to it. When this variable is used in some expression where there is an operand of different datatype, then, the type of this variable will automatically be converted at the time of evaluation. For example, If a variable is initialized as string, and used to perform addition with an integer, then it will be taken as integer at the time of evaluation.
If we want to specify the datatype explicitly, we need to convert it after declaration. There are two ways in converting the data type of variable data. One option is type casting as some languages like C, the other way is to use PHP built-in functions. Both are explained in this article as follows.
php_type_conversion
The type casting method is most familiar one to convert the data type and it’s syntax is,
$variable_name = (data_type) $variavle_name
And, another way to change the type of a variable is implemented by PHP built-in function named as settype(). For example,
<?php
$count = "5";
settype($count,'int');
?>
Since $count is initialized with a value enclosed by double quotes, it’s data type is known as String. After executing the second line of above code, it will be an Integer. To confirm it, we can use gettype() method as shown below.
<?php
$count = "5";
echo gettype($count); // output will be 'string'
settype($count,'int');
echo gettype($count); // output will be 'integer'
?>
In later method, type conversion is going to be done in two steps on making a call to the built in function settype() and then the required conversion will take place. Rather, former method will perform type conversion directly by saving the time of calling settype(). So, it is good programming practice to follow the former one for changing the data type.

PHP Variable Scope

The scope of an variable is a metric about which extent the variable can be visible. There are two main categories in variable scope. These are,
  1. Local scope
  2. Global scope
php_variable_scope

Local Scope:

If the variable is recognized with in particular block structure of the program, then it is called as local variable. For example, if the variable declared inside a function will come under the local scope of that function. The number of arguments passed while calling the function, can also be recognized with in the function.

Global scope:

If variables can be recognized throughout the program, then they are in global scope. Variables in global scope can be used inside functions by using PHP global array variable or by using global keyword.

PHP variable scope example:

<?php
$count = 0;
function calculate_count() {
$count = 5;

//will print 5; the value of local variable
echo ++$count; 

// will print 0; the value of global variable declared outside function
echo $GLOBALS["count"]; 
}
calculate_count();
echo $count;
?>
There is an alternative way to access the global variable inside function discuss above. That is, the use of global keyword for variable declaration will help us in this regard. For that, we need to replace below lines,
global $count;
echo $count;
instead of,
echo $GLOBALS["count"];

PHP Globals with EGPCS Information

PHP contains so many predefined global variables which is called as super globals. These variables are started with an underscore (_) symbol, for example, $_GET, $_POST and etc. Unlike, user defined global variables, this kind of super globals can be accessed from PHP function without using global keyword or anything.
php_global_variable
Super globals used to contain array of information about form contents, sessions, cookies and also have some environment information, which is called as EGPCS information in short. The expansion of this acronym is shown in the below list.
  • $_ENV – This variable contains an array of details about the server environment. For example, $_ENV[“HOME”], $_ENV[“PATH_INFO”] and etc.
  • $_GET – This will contain the list of parameters sent as query string with the url.
  • $_POST – This will have the form parameters and its values when the form method is specified as post
  • $_COOKIE – The registered cookies will be loaded with this array.
  • $_SERVER – It contains the server information like, $_SERVER[“REQUEST_METHOD”], $_SERVER[“QUERY_STRING”] and etc.
While executing the PHP program, the global array data are loaded in the order specified using variables_order directive of the PHP configuration file php.ini, and we can control this order and can decide about which of these variable is required to be displayed. To get the elements of $_GET, $_POST and $_COOKIE as a whole into an single associative array, we can use another PHP global variable named $_REQUEST.

PHP Operators

Like other programming languages, PHP includes set of operators that are used to perform operations between one or more values.
PHP has variety of operators based on the operations to be performed. Each operator has precedence, depends on which order an PHP expression will be executed. Sub expressions that hold operators with higher precedence, are having higher priority during execution.
In this article, we are going to see about various type of PHP operators in the order of their precedence.
php_operators

Auto increment/decrement operators in PHP

This operators can be categorized into two types. These are,
  1. pre increment/decrement. For example,
    echo ++i; // increment before print
    echo --i; // decrement before print
  2. post increment/decrement. For example,
    i++; // increment after print
    i--; // decrement after print
  3. Arithmetic Operators

    Addition (+), Subtraction (-), Division (/), Multiplication (*) and modulus (%) operators are coming under this category. Among them, (+,-) has lower precedence than rest of the arithmetic operators.

    PHP Comparison Operators

    Comparison operators are used in conditional expressions of PHP control flow statements like, if, else if, while and so on. For example,
    while(i<=10) {
     ...
    }
    In PHP, the following comparison operators are available.
    <, >, <=, >=, ==, === and !=
    Among them, the first four operators are having higher precedence than others.

    Logical Operators

    PHP includes the following list of logical operators.
    &&, ||, and, or, xor
    Logical operators represented by symbols and words, i.e. (or and ||) return same result, but vary with the precedence. The symbol representation has two level higher precedence than the word representation of logical operators. Because, assignment and combined assignment operators are having higher precedence than the word representation of logical operators.

    Assignment / combined assignment operators in PHP

    Assignment operators are used either to create a copy of PHP variable or to store some value to the new variable.
    Combined assignment operators are used to reduce the length of the expression and number of operands. For example,
    $i = $i + 1;
    //using combined arithmetic operator
    $i += 1;

    Other additional PHP Operators

    Apart from the above list of operators, PHP includes some additional list of operators. These are,
    • Concatenation operator - dot (.) is used to concatenate two or more strings, or to add HTML code into PHP print statements. For example,
      $user = "PHP Guest";
      echo "Hello" . $user . "<br/>";
    • Conditional operator - ( <condition> ? <if true> : <if false> ). For example,
      $output = $_SESSION["userName"]?$_SESSION["userName"]:"ANONYMOUS";
      echo $output;
    • Backticks - PHP supports to execute shell command, by enclosing it within two backticks (``) in a PHP printing statements. For example,
      $output = `ls -al`;
      echo $output;
    • Suppression operator - (@) is used to suppress any warning or error notice from displaying to the browser. For example,
      @split("-",date("d-m-Y");
      By using @ symbol infront of split function which is deprecated, we can suppress the PHP error message.