PHP MySQL Database Tutorial

MySQL is the most popular database system that is used within PHP. Let's first understand about MySQL.

What is MySQL?

MySQL is open-source Relational Database Management System (RDMS). The name of MySQL is a combination of "My" which is the name of co-founder Michael Widenius's (main author of the original version of open-source MySQL)  daughter, and "SQL" is abstract from Structured Query Language. MySQL used by many popular websites like Facebook, Twitter, and YouTube. MySQL is easy to install. If we install Wamp or Xampp server, then we do not need to install the MySQL database as it is already available in the Wamp or Xampp server.
  • MySQL is a Relational Database Management System (RDMS).
  • MySQL is distributed and developed by Oracle Corp.
  • MySQL is easy to use, fast, powerful, and secure.
  • MySQL can be compiled on several platforms.
  • MySQL is open-source, which means we can freely and easily download and use it.
  • MySQL uses standard SQL.
  • MySQL runs on the server.
MySQL database stores data into tables like another relational database. A table is a collection of data, and it is divided into rows and columns. Databases are useful for storing information sequentially. A university may have a database with the following tables:
  • Student Name
  • Age
  • Batch Year
  • Field
  • Mobile

Downloading MySQL Database

We can download MySQL free from this link: http://www.mysql.com

Relationship between MySQL and PHP?

PHP is used to create a program and MySQL is used to interact with data sets. While developing a PHP application, we need to create a connection to a database. Then we will able to insert, delete, select, and update data. There are multiple ways to use MySQL in a PHP script. Relationship between MySQL and PHP

PHP connect to MySQL

PHP 5 works with MySQL database using:
  • MySQLi ("i" stands for "improved").
  • PDO (PHP Data Objects).
An earlier version of PHP used the MySQL extension. PHP 5 works with MySQL database using

Should we use MySQLi or PDO?

MySQLi or PDO have their advantages:
  • MySQLi only work with MySQL databases, whereas PDO work on 12 different database systems.
  • PDO makes the work easy.
  • If we need to switch our project to use another database, with the help of PDO, we have to change the connection string and a few queries.
  • With MySQLi, we need to re-write the entire code, including quires. 

MySQLi Installation:

For installation details: http://php.net/manual/en/mysqli.installation.php

PDO Installation:

For installation details: http://php.net/manual/en/pdo.installation.php

Connection to MySQL:

Example (MySQLi Object-Oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating Connection
$conn = new mysqli($servername, $username, $password);
// Connection Checking
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Example (MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = mysqli_connect($servername, $username, $password);
// Checking connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
    $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->get Message();
    }
?>

Close the Connection:

The connection can be closed automatically when the script ends. To close the connection before, we can use the following: Example (MySQLi Object-Oriented)
$conn->close();
Example (MySQLi Procedural)
mysqli_close($conn);
Example (PDO)
$conn = null;

PHP Create MySQL Database

Create MySQL Database using MySQLi: The CREATE DATABASE command is used to create a database in MySQL. Create a database name with "details".   Example (MySQLi Object-Oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE details";
if ($conn->query($sql) === TRUE)
{
    echo "Database created successfully";
}
else
 {
    echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
Example MySQLi Procedural
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Creating connection
$conn = mysqli_connect($servername, $username, $password);
// Checking connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Creating database
$sql = "CREATE DATABASE details";
if (mysqli_query($conn, $sql))
{
    echo "Database created successfully";
}
else
 {
    echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Create a database name with "mydetails". Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try
{
    $conn = new PDO("mysql:host=$servername", $username, $password);
    // set the PDO error mode to exception
    $conn-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "CREATE DATABASE mydetails";
    // use exec() because no results are returned
    $conn->exec($sql);
    echo "Database created successfully<br>";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }
$conn = null;
?>
  • PDO has an exception class that is used to handle any problems which may occur in our database queries. If an exception is thrown within the try { } block, the scripts will stop executing and control moves directly to the first catch () {} block.

PHP create MySQL Tables:

A MySQL database table has its unique name, and it consists of rows and columns.

Create a MySQL table using MySQLi:

For creating a table, we use CREATE TABLE command in the MySQL database. We will create a table with a name of "students", which consists of five columns, "id", "first_name", "last_name", "age", and "batch". The columns can hold the data which can specify the data types.

 Attributes for each column:

  • NOT NULL: Every row contains a value for the column. A row cannot be null.
  • DEFAULT: We can set any default value when no value set.
  • AUTOINCREMENT: MySQL automatically increases the value of the field by one each time a new record added.
  • PRIMARY KEY: Used to identify the rows in a table uniquely.
The table should have a primary key column (like "id"). The value of the primary key column must be unique. Example (MySQLi Object-oriented):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "details";
// Creating connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql = "CREATE TABLE students(
id INT(2) AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(30) NOT NULL,
last_name VARCHAR(30) NOT NULL,
age INT(5),
batch VARCHAR(20)
)";
if ($conn->query($sql) === TRUE) {
    echo "Table students created successfully";
}
else {
    echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
Example (MySQLi Procedural):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "details";
// creating connection
$conn = mysqli_connect ($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$sql = "CREATE TABLE students(
id INT(2) AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(30) NOT NULL,
last_name VARCHAR(30) NOT NULL,
age INT(5),
batch VARCHAR(20)
)";
if (mysqli_query($conn, $sql)) {
    echo "Table students created successfully";
} else {
    echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydetails";
try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE TABLE students(
id INT(2) AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(30) NOT NULL,
last_name VARCHAR(30) NOT NULL,
age INT(5),
batch VARCHAR(20)
)";
    // use exec() because no results are returned
    $conn->exec($sql);
    echo "Table students created successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }
$conn = null;
?>

PHP Insert data to MySQL:

Once the database and table created, we can start inserting data into them. Syntax:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
Syntax Rules:
  • The query must be quoted in PHP Language.
  • The string values inside the query must be quoted.
  • The numeric and word value must not be quoted.
  • A column AUTO_INCREMENT ("id") is no need to specify in the SQL query. The MySQL will automatically add the value.
Example (MySQLi Object-Oriented):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "details";
// Creating connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
 {
    die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO students (first_name, last_name, age, batch)
VALUES ('Sonoo', 'Jaiswal', '23', '2015')";
if ($conn->query($sql) === TRUE)
{
    echo "New record created successfully";
}
 else
 {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Example (MySQLi Procedural):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "details";
// Creating connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
    die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO students (first_name, last_name, age, batch)
VALUES ('Sonoo', 'Jaiswal', '23', '2015')";
if (mysqli_query($conn, $sql))
{
    echo "New record created successfully";
}
else
{
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Example (PDO):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydetails";
try
{
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO students (first_name, last_name, age, batch)
VALUES ('Sonoo', 'Jaiswal', '23', '2015')";
  // use exec() because no results are returned
    $conn->exec($sql);
    echo "New record created successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }
$conn = null;
?>

MySQL Insert Multiple Records:

Multiple MySQL commands can be executed with the mysqli_multi_query(). Example (MySQLi Object-Oriented):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "details";
// Creating connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Checking connection
if ($conn->connect_error)
{
    die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO students (first_name, last_name, age, batch)
VALUES ('Sonoo', 'Jaiswal', '23', '2015')";
$sql .= "INSERT INTO students (first_name, last_name, age, batch)
VALUES ('Rahul', 'Jain', '31', '2019')";
$sql .= "INSERT INTO students (first_name, last_name, age, batch)
VALUES ('Mehak', 'Malik', '26', '2014')";
if ($conn->multi_query($sql) === TRUE)
{
    echo "New records created successfully";
}
 else
 {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
  • Each MySQL command must be separated by a semicolon (;).
Example (MySQLi Procedural):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "details";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO students (first_name, last_name, age, batch)
VALUES ('Sonoo', 'Jaiswal', '23', '2015')";
$sql .= "INSERT INTO students (first_name, last_name, age, batch)
VALUES ('Rahul', 'Jain', '31', '2019')";
$sql .= "INSERT INTO students (first_name, last_name, age, batch)
VALUES ('Mehak', 'Malik', '26', '2014')";
if (mysqli_multi_query($conn, $sql)) {
    echo "New records created successfully";
} else {

   echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Example (PDO):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydetails";
try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // begin the transaction
    $conn->beginTransaction();
    // our SQL statements
    $conn->exec("INSERT INTO students (first_name, last_name, age, batch)
VALUES ('Sonoo', 'Jaiswal', '23', '2015')");
    $conn->exec("INSERT INTO students (first_name, last_name, age, batch)
VALUES ('Rahul', 'Jain', '31', '2019')");
    $conn->exec("INSERT INTO students (first_name, last_name, age, batch)
VALUES ('Mehak', 'Malik', '26', '2014')");
    // commit the transaction
    $conn->commit();
    echo "New records created successfully";
    }
catch(PDOException $e)
    {
    // roll back the transaction if something failed
    $conn->rollback();
    echo "Error: " . $e->getMessage();
    }
$conn = null;
?>

PHP select data from MySQL:

The select command is used to select data from one or more tables. Syntax:
SELECT coloumn_name from table_name
The above syntax used to select data from a specified column.
SELECT * from table_name
In the above syntax, the (*) character is used to select data from all the columns.

Select Data with MySQLi:

Example (MySQLi Object-Oriented):
<!DOCTYPE html>
<html>
<body>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "details";
// Creating connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
 {
    die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, first_name, last_name FROM students";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<br> id: ". $row["id"]. " - Name: ". $row["first_name"]. " " . $row"last_name"] . "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();
?>
</body>
</html>
The above example selects the id, first_name, and last_name columns from the Students table.  In the above code, we have set a MySQL query which selects the id, first_name and last_name columns from the Students table. The next line runs the query and puts the output data into a variable which is known as a  $result. The num_row() function is used to check the more than zero rows returned or not.  If the more than zero rows returned, the fetch_assoc() function keeps all the output into an associative array by which we can loop through. The while() loops with the result set and outputs the data by id, first_name, and last_name columns. Example(MySQLi Procedural):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "details";
// Creating connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
 {
    die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, first_name, last_name FROM students";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{
    // output data of each row
    while($row = mysqli_fetch_assoc($result))
{
        echo "id: " . $row["id"]. " - Name: " . $row["first_name"]. " " . $row"last_name"]. "<br>";
    }
}
else
{
    echo "0 results";
}
mysqli_close($conn);
?>

 Select Data With PDO:

Example (PDO):
<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr>
<th>Id</th>
<th>Firstname</th>
<th>Lastname</th></tr>";
class TableRows extends RecursiveIteratorIterator
 {
    function __construct($it)
{
        parent::__construct($it, self::LEAVES_ONLY);
    }
    function current()
 {
        return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
    }
    function beginChildren()
{
        echo "<tr>";
    }
    function endChildren()
{
        echo "</tr>" . "\n";
    }
}
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydetails";
Try
 {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT id, first_name, last_name FROM students");
    $stmt->execute();
    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v)
 {
        echo $v;
    }
}
catch(PDOException $e)
{
    echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>

Delete Data from a MySQL:

The DELETE command is used to delete a data/record from a table. Syntax:
DELETE FROM table_name
WHERE column_name = value.
  • column_name: from which column we want to pick a value.
  • value: which value we want to delete from the selected column.
"STUDENTS" Table:
Id First_name Last_name Age Batch
1 Sonoo Jaiswal 23 2015
2 Rahul Jain 31 2019
3 Mehak Malik 26 2014
Example (MySQLi Object-Oriented):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "details";
// Creating connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Checking connection
if ($conn->connect_error)
{
    die("Connection failed: " . $conn->connect_error);
}
//deleting a record
$sql = "DELETE FROM students WHERE id=3";
if ($conn->query($sql) === TRUE)
{
    echo "Record deleted successfully";
}
 else
{
    echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
Example (MySQLi Procedural):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "details";
// Creating connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Checking connection
if (!$conn)
{
    die("Connection failed: " . mysqli_connect_error());
}
//deleting a record
$sql = "DELETE FROM students WHERE id=3";
if (mysqli_query($conn, $sql))
{
    echo "Record deleted successfully";
}
 else
{
    echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Example(PDO):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydetails";
try
{
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //deleting a record
    $sql = "DELETE FROM students WHERE id=3";
    // use exec() because no results are returned
    $conn->exec($sql);
    echo "Record deleted successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }
$conn = null;
?>
Let`s look at the "students" table after deletion of record:
Id First_name Last_name Age Batch
1 Sonoo Jaiswal 23 2015
2 Rahul Jain 31 2019

PHP Update Data in MySQL:

The UPDATE command is used to update existing records in a table. "STUDENTS" Table:
Id First_name Last_name Age Batch
1 Sonoo Jaiswal 23 2015
2 Rahul Jain 31 2019
Example (MySQLi Object-Oriented):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "details";
// Creating connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Checking connection
if ($conn->connect_error)
{
    die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE students SET last_name='Jain' WHERE id=2";
if ($conn->query($sql) === TRUE)
{
    echo "Record updated successfully";
}
else
 {
    echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
Example (MySQLi Procedural):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "details";
// Creating connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Checking connection
if (!$conn)
 {
    die("Connection failed: " . mysqli_connect_error());
}
$sql = "UPDATE students SET last_name='Jain' WHERE id=2";
if (mysqli_query($conn, $sql))
{
    echo "Record updated successfully";
}
 else
{
    echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Example (PDO):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydetails";
try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "UPDATE students SET last_name='Jain' WHERE id=2";
    // Preparing statement
    $stmt = $conn->prepare($sql);
    // executing the query
    $stmt->execute();
    echo $stmt->rowCount() . " records UPDATED successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }
$conn = null;
?>
Let`s look at the "students" table after updated the record:
Id First_name Last_name Age Batch
1 Sonoo Jain 23 2015
2 Rahul Jain 31 2019

PHP Limit Data from MySQL:

LIMIT clause is used to define the number of records to return. The LIMIT clause makes the code easy for multi-page results and pagination with MySQL, which is very useful on large tables. Returning a large number of records can impact on performance.
$sql = "SELECT * FROM Employee LIMIT 10";
In the above code, we have selected all the records from 1-10 from a table called "Employee". When the above query runs, it will return the first 10 records.

Related Topics

PHP array_fill_keys() Function

The array_fill_keys() function in PHP fills an array with the value of the specified value parameter, using the values of the specified keys array as keys. Syntax array_fill_keys ( array $keys , mixed $value ) Parameter keys(required)- This parameter signifies the input array of values that will be...

1 minute read.

PHP str_split() Function

PHP str_split() Function The str_split() function in PHP splits a string into an array. String str_split ( string $string [, int $split_length = 1 ] ) Parameter string(required)- This parameter represents the input string. split_length(optional)- This parameter signifies the maximum length of the chunk. The default value is 1. Return This function...

2 minutes read.

PHP intval() Function

The intval() Function in PHP is used to get the integer value for the given variable. This function should not be used on objects. Else it will emit an E_NOTICE level error and return 1. Syntax intval...

1 minute read.

PHP array_diff_assoc() Function

PHP array_diff_assoc() Function The array_diff_assoc() Function in PHP compares the difference of arrays and returns an array containing all the values from array1 that are not present in any of the other arrays. Syntax array_diff_assoc ( array $array1 , array $array2 [, array $... ] ) Parameter array1(required)- This parameter signifies...

1 minute read.

PHP substr_compare() Function

PHP substr_compare() Function The substr_compare() function in PHP compares two strings from a specified start position. It is a binary-safe and optionally case-sensitive function. Syntax substr_compare ( string $main_str , string $str , int $offset [, int $length [, bool$case_insensitivity]] )  Parameter main_str(required)- This parameter specifies the first string to compare. str(required)- This parameter...

1 minute read.

PHP substr_replace() Function

PHP substr_replace() Function The substr_replace() function in PHP replaces a part of a string with another string. Syntax substr_replace (mixed $string , mixed $replacement , mixed $start [, mixed $length ] ) Parameter string(required)- This parameter represents the input string. replacement(required)- This parameter signifies the string to replace with. start(required)-...

2 minutes read.

PHP Comment

PHP commentis a line of code that is not executed. It is often used by developer to understand the code. PHP support single and multiple comments. In other language like C,...

1 minute read.

PHP array_splice() Function

PHP array_splice() Function The array_splice() function in PHP is used to remove a portion of the array and replaces them with the elements of the replacement array. Syntax array_splice (array &$input, int $offset [, int $length = count($input) [, mixed $replacement = array() ]] ) Parameter input(required)- This array represents the...

2 minutes read.

PHP strtok() Function

PHP strtok() Function The strtok() function in PHP splits a string into smaller strings or tokenize the specified string.  Syntax strtok ( string $str , string $token ) Parameter str(required)- This parameter represents the input string to split into smaller strings or tokens. token(required)- It signifies...

1 minute read.

PHP sha1() Function

PHP sha1() Function The sha1() in PHP calculates the SHA-1 hash of a string. Syntax sha1 ( string $str [, bool $raw_output = FALSE ] )  Parameter str (required)- This parameter represents the input string. raw_output(optional)- This parameter takes Boolean value and returns the digest in raw binary format...

1 minute read.

PHP is_array() Function

The is_array() Function in PHP is used to  find whether a variable is an array or not. It returns a Boolean value true if the parameter var is an array else it returns...

1 minute read.

PHP array() function

PHP array() function The array() function in PHP is used to create an array. Syntax array ([ mixed $... ] ) Parameter …(optional)- This parameter represents the elements’ values along with keys of the array. The syntax of this is as follows: "index => values"...

1 minute read.

PHP str_word_count() Function

PHP str_word_count() Function The str_word_count() function in PHP counts the number of words inside the string and returns the information about words used in a string. String str_word_count( string $string [, int $format [, string $charlist ]] ) Parameter string(required)- This parameter represents the input string. format(required)- This parameterspecifies the...

2 minutes read.

PHP foreach Loop

PHP foreach Loop with Example PHP foreach loop is used to loop through the associative arrays. Syntax: foreach($array as $key => $value) { //Statement } $array = associative array. $key = array key. &value =...

2 minutes read.

PHP String

PHP string is a sequence of characters. It is used to store and manipulate text. We can specify a string literal in four ways: single quoted double quoted heredoc syntax ...

2 minutes read.

PHP pos() Function

PHP pos() Function The pos() function in PHP returns the current element in an array which is initialized to the first element of the array. This function is an alias of current(). Syntax pos ( array...

1 minute read.

PHP unserialize() Function

PHP unserialize() Function The unserialize() function in PHP takes a single serialized variable and converts it back into a PHP value. Syntax unserialize ( string $str [, array $options ] ) Parameter value(required)- This parameter represents the serialized string. options(optional)- This parameter signifies any options to be...

1 minute read.

PHP parse_str() Function

PHP parse_str() Function The parse_str() function in PHP parses a query string into variables. Syntax parse_str ( string $encoded_string [, array &$result ] ) Parameter encoded_string(required)- This parameter represents the input string. result(optional)- This parameter specifies the name of an...

1 minute read.

PHP setlocale() Function

PHP setlocale() Function The setlocale() function in PHP sets locale information(language, monetary, time and, other information specific for a geographical area.) Syntax setlocale ( int $category , array $locale ) Parameter category(required)- This parameter specified a named constant specifying the category of the functions affected...

1 minute read.

PHP is_resource() Function

PHP is_resource() Function The is_resource() function in PHP finds whether a variable is a resource or not. It returns a Boolean value TRUE if the parameter var is resource, else it returns FALSE Syntax is_resource ( mixed $var ) Parameter var(required)- This parameter represents the value to check. Return This function...

1 minute read.