PHP MySQL Select Query

PHP mysql_query() function is used to execute select query. Since PHP 5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2 alternatives.

  • mysqli_query()
  • PDO::__query()

There are two other MySQLi functions used in select query.

  • mysqli_num_rows(mysqli_result $result): returns number of rows.
  • mysqli_fetch_assoc(mysqli_result $result): returns row as an associative array. Each key of the array represents the column name of the table. It return NULL if there are no more rows.

PHP MySQLi Select Query Example

Example

 

<?php  
$host = 'localhost:3306';  
$user = '';  
$pass = '';  
$dbname = 'test';  
$conn = mysqli_connect($host, $user, $pass,$dbname);  
if(!$conn){  
  die('Could not connect: '.mysqli_connect_error());  
}  
echo 'Connected successfully<br/>';  
  
$sql = 'SELECT * FROM emp4';  
$retval=mysqli_query($conn, $sql);  
  
if(mysqli_num_rows($retval) > 0){  
 while($row = mysqli_fetch_assoc($retval)){  
    echo "EMP ID :{$row['id']}  <br> ".  
         "EMP NAME : {$row['name']} <br> ".  
         "EMP SALARY : {$row['salary']} <br> ".  
         "--------------------------------<br>";  
 } //end of while  
}else{  
echo "0 results";  
}  
mysqli_close($conn);  
?> 

Output:

Connected successfully
EMP ID :1 
EMP NAME : ratan 
EMP SALARY : 9000 
--------------------------------
EMP ID :2 
EMP NAME : karan 
EMP SALARY : 40000 
--------------------------------
EMP ID :3 
EMP NAME : jai 
EMP SALARY : 90000 
--------------------------------

PHP Call By Value and reference

PHP Call By Value

PHP allows you to call function by value and reference both. In case of PHP call by value, actual value is not modified if it is modified inside the function.

Let’s understand the concept of call by value by the help of examples.

Example 1

In this example, variable $str is passed to the adder function where it is concatenated with ‘Call By Value’ string. But, printing $str variable results ‘Hello’ only. It is because changes are done in the local variable $str2 only. It doesn’t reflect to $str variable.

<?php  
function adder($str2)  
{  
    $str2 .= 'Call By Value';  
}  
$str = 'Hello ';  
adder($str);  
echo $str;  
?>  

Output:

Hello

Example 2

Let’s understand PHP call by value concept through another example.

<?php  
function increment($i)  
{  
    $i++;  
}  
$i = 10;  
increment($i);  
echo $i;  
?> 

Output:

10

PHP Call By Reference

In case of PHP call by reference, actual value is modified if it is modified inside the function. In such case, you need to use & (ampersand) symbol with formal arguments. The & represents reference of the variable.

Let’s understand the concept of call by reference by the help of examples.

Example 1

In this example, variable $str is passed to the adder function where it is concatenated with ‘Call By Reference’ string. Here, printing $str variable results ‘This is Call By Reference’. It is because changes are done in the actual variable $str.

<?php  
function adder(&$str2)  
{  
    $str2 .= 'Call By Reference';  
}  
$str = 'This is ';  
adder($str);  
echo $str;  
?>  

Output:

This is Call By Reference

Example 2

Let’s understand PHP call by reference concept through another example.

<?php  
function increment(&$i)  
{  
    $i++;  
}  
$i = 10;  
increment($i);  
echo $i;  
?>  

Output:

11

PHP Switch

PHP switch statement is used to execute one statement from multiple conditions. It works like PHP if-else-if statement.

Syntax

switch(expression){      
case value1:      
 //code to be executed  
 break;  
case value2:      
 //code to be executed  
 break;  
......      
default:       
 code to be executed if all cases are not matched;    
}  

Important points to be noticed about switch case:

  1. The default is an optional statement. Even it is not important, that default must always be the last statement.
  2. There can be only one default in a switch statement. More than one default may lead to a Fatal error.
  3. Each case can have a break statement, which is used to terminate the sequence of statement.
  4. The break statement is optional to use in switch. If break is not used, all the statements will execute after finding matched case value.
  5. PHP allows you to use number, character, string, as well as functions in switch expression.
  6. Nesting of switch statements is allowed, but it makes the program more complex and less readable.
  7. You can use semicolon (;) instead of colon (:). It will not generate any error.

PHP Switch Example

<?php      
$num=20;      
switch($num){      
case 10:      
echo("number is equals to 10");      
break;      
case 20:      
echo("number is equal to 20");      
break;      
case 30:      
echo("number is equal to 30");      
break;      
default:      
echo("number is not equal to 10, 20 or 30");      
}     
?>  

Output:

number is equal to 20

PHP switch statement with character

Program to check Vowel and consonant

We will pass a character in switch expression to check whether it is vowel or constant. If the passed character is A, E, I, O, or U, it will be vowel otherwise consonant.

<?php      
    $ch = 'U';  
    switch ($ch)  
    {     
        case 'a':   
            echo "Given character is vowel";  
            break;  
        case 'e':   
            echo "Given character is vowel";  
            break;  
        case 'i':   
            echo "Given character is vowel";  
            break;  
        case 'o':   
            echo "Given character is vowel";  
            break;    
        case 'u':   
            echo "Given character is vowel";  
            break;  
        case 'A':   
            echo "Given character is vowel";  
            break;  
        case 'E':   
            echo "Given character is vowel";  
            break;  
        case 'I':   
            echo "Given character is vowel";  
            break;  
        case 'O':   
            echo "Given character is vowel";  
            break;  
        case 'U':   
            echo "Given character is vowel";  
            break;  
        default:   
            echo "Given character is consonant";  
            break;  
    }  
?>  

Output:

Given character is vowel

PHP switch statement with String

PHP allows to pass string in switch expression. Let’s see the below example of course duration by passing string in switch case statement.

<?php      
    $ch = "B.Tech";  
    switch ($ch)  
    {     
        case "BCA":   
            echo "BCA is 3 years course";  
            break;  
        case "Bsc":   
            echo "Bsc is 3 years course";  
            break;  
        case "B.Tech":   
            echo "B.Tech is 4 years course";  
            break;  
        case "B.Arch":   
            echo "B.Arch is 5 years course";  
            break;  
        default:   
            echo "Wrong Choice";  
            break;  
    }  
?>

Output:

B.Tech is 4 years course

PHP switch statement is fall-through

PHP switch statement is fall-through. It means it will execute all statements after getting the first match, if break statement is not found.

<?php      
    $ch = 'c';  
    switch ($ch)  
    {     
        case 'a':   
            echo "Choice a";  
            break;  
        case 'b':   
            echo "Choice b";  
            break;  
        case 'c':   
            echo "Choice c";      
            echo "</br>";  
        case 'd':   
            echo "Choice d";  
            echo "</br>";  
        default:   
            echo "case a, b, c, and d is not found";  
    }  
?>  

Output:

Choice c
Choice d
case a, b, c, and d is not found

PHP nested switch statement

Nested switch statement means switch statement inside another switch statement. Sometimes it leads to confusion.

<?php      
    $car = "Hyundai";                   
        $model = "Tucson";    
        switch( $car )    
        {    
            case "Honda":    
                switch( $model )     
                {    
                    case "Amaze":    
                           echo "Honda Amaze price is 5.93 - 9.79 Lakh.";   
                        break;    
                    case "City":    
                           echo "Honda City price is 9.91 - 14.31 Lakh.";    
                        break;     
                }    
                break;    
            case "Renault":    
                switch( $model )     
                {    
                    case "Duster":    
                        echo "Renault Duster price is 9.15 - 14.83 L.";  
                        break;    
                    case "Kwid":    
                           echo "Renault Kwid price is 3.15 - 5.44 L.";  
                        break;    
                }    
                break;    
            case "Hyundai":    
                switch( $model )     
                {    
                    case "Creta":    
                        echo "Hyundai Creta price is 11.42 - 18.73 L.";  
                        break;    
        case "Tucson":    
                           echo "Hyundai Tucson price is 22.39 - 32.07 L.";  
                        break;   
                    case "Xcent":    
                           echo "Hyundai Xcent price is 6.5 - 10.05 L.";  
                        break;    
                }    
                break;     
        }  
?> 

Output:

Hyundai Tucson price is 22.39 - 32.07 L.

PHP Comments

PHP comments can be used to describe any line of code so that other developer can understand the code easily. It can also be used to hide any code.

PHP supports single line and multi line comments. These comments are similar to C/C++ and Perl style (Unix shell style) comments.

PHP Single Line Comments

There are two ways to use single line comments in PHP.

  • // (C++ style single line comment)
  • # (Unix Shell style single line comment)
<?php  
// this is C++ style single line comment  
# this is Unix Shell style single line comment  
echo "Welcome to PHP single line comments";  
?>  

Output:Welcome to PHP single line comments

PHP Multi Line Comments

In PHP, we can comments multiple lines also. To do so, we need to enclose all lines within /* */. Let’s see a simple example of PHP multiple line comment.

<?php  
/* 
Anything placed 
within comment 
will not be displayed 
on the browser; 
*/  
echo "Welcome to PHP multi line comment";  
?> 

Output:Welcome to PHP multi line comment