Database connection using PHP MySqli

For PHP freshers, one important thing is mysql_* functions are deprecated. Instead of mysql_* functions now we use mysqli_* functions.

PHP mysqli_connect() Function is used for connection to mysql database.




Example
Open a new connection to the MySQL server:

<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?>


If we are using wamp or xamp on localhost,
my_user = root

my_password = "" (blank/empty)
my_db = your database name


This function returns an object representing the connection to the MySQL server, the returned connection object is used for executing mysql queries.


Insert Data Into MySQL Using MySQLi:
The INSERT INTO statement is used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

Example:
The following examples add a new record to the "MyGuests" table:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";

if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>


In this way, we just understood the concept and basics of mysqli connection.



Multidimensional Arrays in PHP: syntax and example

Multidimensional Arrays in PHP:
In previous post Arrays in PHP we learned Arrays and types of arrays.
We understood the concept of regular array that is indexed array, it is also called numeric array. We understood associative array.

Now we are going to understand Multidimensional array.
A multidimensional array is an array containing one or more arrays. It is also called array of array.

A multi-dimensional array each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple index.

Two-dimensional Arrays:
A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of arrays).




example:
<?php
$students=array(
          array('Vanesh', 'MCA', '78'),
          array('Ganesh', 'MCM', '83'),
          array('Ramesh', 'MSC', '64'),
);

echo $students[0][0]." ".$students[0][1]." ".$students[0][2]. "<br/>";
echo $students[1][0]." ".$students[1][1]." ".$students[1][2]. "<br/>";
echo $students[2][0]." ".$students[2][1]." ".$students[2][2]. "<br/>";

?>


output:
Vanesh MCA 78
Ganesh MCM 83
Ramesh MSC 64

We can print this array using foreach loop as:

<?php
$students=array(
          array('Vanesh', 'MCA', '78'),
          array('Ganesh', 'MCM', '83'),
          array('Ramesh', 'MSC', '64'),
);
foreach($students as $key => $val){
  foreach($val as $v){
      echo $v." ";
    }
  echo "<br/>";
}
?>

output:
Vanesh MCA 78
Ganesh MCM 83
Ramesh MSC 64

Arrays in PHP

Arrays in PHP:
An array stores multiple values in one single variable.




An array is a data structure that stores one or more similar type of values in a single value.

Types of array:

There are three different kind of arrays and each array value is accessed using an ID c which is called array index.

Numeric array − An array with a numeric index. Values are stored and accessed in linear fashion.

Associative array − An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.

Multidimensional array − An array containing one or more arrays and values are accessed using multiple indices.

Numeric Array
These arrays can store numbers, strings and any object but their index will be represented by numbers. By default array index starts from zero.

Example
Following is the example showing how to create and access numeric arrays.

Here we have used array() function to create array. In PHP, the array() function is used to create an array.

<?php
         /* First method to create array. */
         $numbers = array( 1, 2, 3, 4, 5);
         
         foreach( $numbers as $value ) {
            echo "Value is $value <br />";
         }
         
         /* Second method to create array. */
         $numbers[0] = "one";
         $numbers[1] = "two";
         $numbers[2] = "three";
         $numbers[3] = "four";
         $numbers[4] = "five";
         
         foreach( $numbers as $value ) {
            echo "Value is $value <br />";
         }
      ?>

Output:
Value is 1 
Value is 2 
Value is 3 
Value is 4 
Value is 5 
Value is one 
Value is two 
Value is three 
Value is four 
Value is five 

Associative Arrays:
Associative arrays are arrays that use named keys that you assign to them.

There are two ways to create an associative array:

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

or:

$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
The named keys can then be used in a script:

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

OUTPUT:
Peter is 35 years old.

Loop Through an Associative Array
To loop through and print all the values of an associative array, you could use a foreach loop, like this:

Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {
    echo "Key=" . $x . ", Value=" . $x_value;
    echo "<br>";
}
?>

OUTPUT:
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43




Multidimensional Arrays:

Multidimensional Arrays will learn in next lession. 

For loop in PHP : Introduction with Example

The PHP for Loop:



The for loop is used when you know how many times you want to execute a statement or a block of statements.

Today we are going to learn for loop in php.

Syntax:

for (init counter; test counter; increment counter) {
    code to be executed;
}

Parameters:

init counter: Initialize the loop counter value
test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
increment counter: Increases the loop counter value

The example below displays the numbers from 0 to 10:

Example
<?php 
for ($x = 0; $x <= 10; $x++) {
    echo "The number is: $x <br>";

?>

OUTPUT:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10




Important PHP string functions

PHP string functions:
In this post we will look at some commonly used functions to manipulate strings.

Note: It is important for Interview questions.




strlen() function in PHP:
The PHP strlen() function returns the length of a string.
The example below returns the length of the string "Welcome to PHP":

Example

<?php

echo strlen("Welcome to PHP"); // OUTPUT: 14

?>

In above example "Welcome to PHP" this parameter passed to strlen() function and we used echo statement so it prints 14 as a output.
Welcome=7
to=2
PHP=3
2 sapces.

strtoupper() function in PHP:
The strtoupper() function converts a string to uppercase.
Example
Convert all characters to uppercase:

<?php

echo strtoupper("Hello WORLD!"); 
// OUTPUT: HELLO WORLD!

?>

strtolower() function in PHP:
The strtolower() function converts a string to lowercase.
Example
Convert all characters to lowercase:

<?php

echo strtolower("Hello WORLD."); // OUTPUT: hello world.

?>

ucfirst() function in PHP:
The ucfirst() function converts the first character of a string to uppercase.
Example
Convert the first character of "hello" to uppercase:

<?php

echo ucfirst("hello world!"); // OUTPUT: Hello world!

?>


ucwords() function in PHP:
The ucwords() function converts the first character of each word in a string to uppercase.
Example
Convert the first character of each word to uppercase:

<?php

echo ucwords("hello world"); // OUTPUT: Hello World!

?>

strrev() function in PHP:
The PHP strrev() function reverses a string:
Example:

<?php

echo strrev("Vanesh"); // OUTPUT: hsenaV

?>

strpos() function in PHP:
The PHP strpos() function searches for a specific text within a string.
If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE.

The example below searches for the text "world" in the string "Hello world!":

Example
<?php

echo strpos("Hello world!", "world"); // OUTPUT: 6

?>

str_replace() function  in PHP:
 - Replace Text Within a String
The PHP str_replace() function replaces some characters with some other characters in a string.

The example below replaces the text "world" with "Dolly":

Example
<?php

echo str_replace("world", "Vanesh", "Hello world!"); 
// OUTPUT: Hello Vanesh!

?>

strstr() Function in PHP:

Example
Find the first occurrence of "world" inside "Hello world!" and return the rest of the string:

<?php

echo strstr("Hello world!","world");

?>

OUTPUT: world!
The strstr() function searches for the first occurrence of a string inside another string.
This function is case-sensitive. For a case-insensitive search, use stristr() function.
Important: It returns the rest of the string (from the matching point), or FALSE, if the string to search for is not found.

str_repeat() function in PHP:
Repeats a string a specified number of times.

Example
Repeat the string "v" 10 times:

<?php

echo str_repeat("v",10); 
// OUTPUT: vvvvvvvvvv

?>

substr() function in PHP:
The substr() function returns a part of a string.

Example
Return "world" from the string:

<?php

echo substr("Hello world",6); 
// OUTPUT: world

?>

Above php string functions are very important, and important for Interview Questions.