PHP MySQL Insert Record

PHP mysql_query() function is used to insert record in a table. Since PHP 5.5, mysql_query() function is deprecated. Now it is recommended to use one of the 2 alternatives.

  • mysqli_query()
  • PDO::__query()

PHP MySQLi Insert Record 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 = 'INSERT INTO emp4(name,salary) VALUES ("sonoo", 9000)';  
if(mysqli_query($conn, $sql)){  
 echo "Record inserted successfully";  
}else{  
echo "Could not insert record: ". mysqli_error($conn);  
}  
  
mysqli_close($conn);  
?>

Output:

Connected successfully
Record inserted successfully

PHP MySQL Create Table

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

  • mysqli_query()
  • PDO::__query()

PHP MySQLi Create Table 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 = "create table emp5(id INT AUTO_INCREMENT,name VARCHAR(20) NOT NULL,  
emp_salary INT NOT NULL,primary key (id))";  
if(mysqli_query($conn, $sql)){  
 echo "Table emp5 created successfully";  
}else{  
echo "Could not create table: ". mysqli_error($conn);  
}  
  
mysqli_close($conn);  
?>  

Output:

Connected successfully
Table emp5 created successfully

PHP MySQL Create Database

Since PHP 4.3, mysql_create_db() function is deprecated. Now it is recommended to use one of the 2 alternatives.

  • mysqli_query()
  • PDO::__query()

PHP MySQLi Create Database Example

Example

<?php  
$host = 'localhost:3306';  
$user = '';  
$pass = '';  
$conn = mysqli_connect($host, $user, $pass);  
if(! $conn )  
{  
  die('Could not connect: ' . mysqli_connect_error());  
}  
echo 'Connected successfully<br/>';  
  
$sql = 'CREATE Database mydb';  
if(mysqli_query( $conn,$sql)){  
  echo "Database mydb created successfully.";  
}else{  
echo "Sorry, database creation failed ".mysqli_error($conn);  
}  
mysqli_close($conn);  
?>  

Output:

Connected successfully
Database mydb created successfully.

PHP With OOPS Concept

Object-oriented programming is a programming model organized around Object rather than the actions and data rather than logic.

Class:

A class is an entity that determines how an object will behave and what the object will contain. In other words, it is a blueprint or a set of instruction to build a specific type of object.

In PHP, declare a class using the class keyword, followed by the name of the class and a set of curly braces ({}).

This is the blueprint of the construction work that is class, and the houses and apartments made by this blueprint are the objects.

Syntax to Create Class in PHP

  1.   
<?php  
class MyClass  
    {  
        // Class properties and methods go here  
    }  
?>

Important note:

In PHP, to see the contents of the class, use var_dump(). The var_dump() function is used to display the structured information (type and value) about one or more variables.

Syntax:

  1. var_dump($obj);  

Object:

A class defines an individual instance of the data structure. We define a class once and then make many objects that belong to it. Objects are also known as an instance.

An object is something that can perform a set of related activities.

Syntax:

  

<?php  
class MyClass  
{  
        // Class properties and methods go here  
}  
$obj = new MyClass;  
var_dump($obj);  
?>

Example of class and object:

<?php  
class demo  
{  
        private $a= "hello tutorialspro";  
        public function display()  
        {  
        echo $this->a;  
        }  
}  
$obj = new demo();  
    $obj->display();  
?>  

Output:

hello tutorialspro

Example 2: Use of var_dump($obj);

  

<?php  
class demo  
{  
        private $a= "hello javatpoint";  
        public function display()  
        {  
        echo $this->a;  
        }  
}  
$obj = new demo();  
    $obj->display();  
    var_dump($obj);  
?>

Output:

hello tutorialspro

object(demo)[1]

private ‘a’ => string ‘hello tutorialspro’ (length=18)

JavaScript User-defined Object Type

This tutorial covers the concept of the user-defined object type in JavaScript. We have already covered JavaScript object which is created using object initializer syntax or the Object constructor syntax, and instance of an Object type is created.

Just like the default Object type, using which we can create objects in JavaScript, we can define our custom type using which we can create custom objects in JavaScript.

Creating User-defined JavaScript Object Type

We can define a custom object type by writing a constructor function where the name of the function should start with an uppercase alphabet for example CarCupHuman, etc.

The constructor function is defined just as we define any other user-defined JavaScript Function.

Here is the syntax for defining a constructor function:

function Xyz(param1, param2, ... , paramN)
{
    this.param1 = param1;
    this.param2 = param2;
    ...
    this.paramN = paramN;    
}

Once we have the constructor function defined, we can use it to create an object using the new keyword as follows:

let customObj = new Xyz(paramValue1, paramValue2, paramValue3, ... , paramValueN);

Using this Keyword

In JavaScript we use this keyword to reference the current object, hence in the constructor function we create new properties (param1param2, …) for the object type and we set the values for the parameters provided at the time of object creation using the new keyword.

Few Points to Remember:

  1. We can update the constructor function as many times we want, adding more properties or removing properties from it.
  2. We can also store another object in an object’s property while creating the object uwing the new keyword.
  3. We can use default parameters to specify default values and Rest parameters while defining a user-defined object type’s constructor function.

Now let’s take a few examples to see how we can define a custom object type and create an object using the new keyword.

User-defined JavaScript Object Type Example

In the below code example we have created a new constructor function for object type Bike, and then created an object using the new keyword.

<!-- wp:paragraph -->
<p>This tutorial covers the concept of the user-defined object type in JavaScript. We have already covered&nbsp;JavaScript object&nbsp;which is created using&nbsp;<strong>object initializer syntax</strong>&nbsp;or the&nbsp;<strong>Object constructor</strong>&nbsp;syntax, and instance of an&nbsp;<code>Object</code>&nbsp;type is created.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Just like the default Object type, using which we can create objects in JavaScript, we can define our custom type using which we can create custom objects in JavaScript.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Creating User-defined JavaScript Object Type</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>We can define a custom object type by writing a constructor function where the name of the function should start with an uppercase alphabet for example&nbsp;<em>Car</em>,&nbsp;<em>Cup</em>,&nbsp;<em>Human</em>, etc.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The constructor function is defined just as we define any other user-defined&nbsp;JavaScript Function.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here is the&nbsp;<strong>syntax for defining a constructor function</strong>:</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code -->
<pre class="wp-block-syntaxhighlighter-code">function Xyz(param1, param2, ... , paramN)
{
    this.param1 = param1;
    this.param2 = param2;
    ...
    this.paramN = paramN;    
}</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>Once we have the constructor function defined, we can use it to create an object using the&nbsp;<code>new</code>&nbsp;keyword as follows:</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code -->
<pre class="wp-block-syntaxhighlighter-code">let customObj = new Xyz(paramValue1, paramValue2, paramValue3, ... , paramValueN);</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:heading {"level":3} -->
<h3>Using&nbsp;<code>this</code>&nbsp;Keyword</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In JavaScript we use&nbsp;<code>this</code>&nbsp;keyword to reference the current object, hence in the constructor function we create new properties (<em>param1</em>,&nbsp;<em>param2</em>, ...) for the object type and we set the values for the parameters provided at the time of object creation using the&nbsp;<code>new</code>&nbsp;keyword.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Few Points to Remember:</h3>
<!-- /wp:heading -->

<!-- wp:list {"ordered":true} -->
<ol><li>We can update the constructor function as many times we want, adding more properties or removing properties from it.</li><li>We can also store another object in an object's property while creating the object uwing the&nbsp;<code>new</code>&nbsp;keyword.</li><li>We can use&nbsp;default parameters&nbsp;to specify default values and&nbsp;Rest parameters&nbsp;while defining a user-defined object type's constructor function.</li></ol>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Now let's take a few examples to see how we can define a custom object type and create an object using the&nbsp;<code>new</code>&nbsp;keyword.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>User-defined JavaScript Object Type Example</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>In the below code example we have created a new constructor function for object type&nbsp;<strong>Bike</strong>, and then created an object using the&nbsp;<code>new</code>&nbsp;keyword.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We can create as many objects of type Bike once we have defined the constructor function for it. We can set different property values while creating objects. For example,</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code -->
<pre class="wp-block-syntaxhighlighter-code">let myBike = new Bike("KTM", "Duke", 2020);
let yourBike = new Bike("Royal Enfield", "Classis", 2020);</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>We can compare these objects using JavaScript operators and perform a lot of other operations too.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Using a user-defined Object as Property of another Object</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Let's define one more object type and then use it as a value in our&nbsp;<strong>Bike</strong>&nbsp;object type.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We have defined a new object type&nbsp;<strong>Person</strong>&nbsp;below, and have also added a new property&nbsp;<strong>owner</strong>&nbsp;in the&nbsp;<strong>Bike</strong>&nbsp;object type in which we will store the&nbsp;<strong>Person</strong>&nbsp;objects.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We can do anything with user-defined object types in JavaScript.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Using the&nbsp;<code>Object.create</code>&nbsp;method</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>If you do not want to get into the trouble of defining a constructor method to define a user-defined object type, you can use the Object.create() method to create an object of any prototype object which is already defined.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's take an example to understand this.</p>
<!-- /wp:paragraph -->

<!-- wp:syntaxhighlighter/code -->
<pre class="wp-block-syntaxhighlighter-code">let Bike = {
    company: 'KTM',  // Default value of properties
    model: 'Duke 390',
    show: function() {  // Method to display property type of Bike
        document.write(this.company+" "+this.model);
    }
};

// using Object.create to create a new object
let newBike = Object.create(Bike);
newBike.company = 'Yamaha';
newBike.model = 'R15';
newBike.show();</pre>
<!-- /wp:syntaxhighlighter/code -->

<!-- wp:paragraph -->
<p>Yamaha R15</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>As you can see in the code above, we can use the&nbsp;<code>Object.create</code>&nbsp;method to create a new object using an already defined object, and then if required we can change the properties values and use the object function too.</p>
<!-- /wp:paragraph -->

<!-- wp:buttons -->
<div class="wp-block-buttons"><!-- wp:button -->
<div class="wp-block-button"><a class="wp-block-button__link" href="https://wp.me/pc22El-Vx">< prev</a></div>
<!-- /wp:button -->

<!-- wp:button -->
<div class="wp-block-button"><a class="wp-block-button__link" href="https://wp.me/pc22El-VP">next ></a></div>
<!-- /wp:button --></div>
<!-- /wp:buttons -->

We can create as many objects of type Bike once we have defined the constructor function for it. We can set different property values while creating objects. For example,

let myBike = new Bike("KTM", "Duke", 2020);
let yourBike = new Bike("Royal Enfield", "Classis", 2020);

We can compare these objects using JavaScript operators and perform a lot of other operations too.

Using a user-defined Object as Property of another Object

Let’s define one more object type and then use it as a value in our Bike object type.

<!doctype html>
	<head>
		<title>Object in Object Example JavaScript</title>
	</head>
	<body>
		<script>
			/* defining a new constructor function */
			function Person(name, age, city) {
                this.name = name;
                this.age = age;
                this.city = city;
            }
            
            function Bike(company, model, year, owner) {
                this.company = company;
                this.model = model;
                this.year = year;
                this.owner = owner;
            }
            
            /* creating the object */
            let john = new Person("John Wick", 30, "New York");
            let myBike = new Bike("KTM", "Duke", 2010, john);
            
            document.write(myBike.company+"<br/>"+myBike.model+"<br/>"+myBike.year+"<br/>"+myBike.owner.name);
		</script>
	</body>
</html>

We have defined a new object type Person below, and have also added a new property owner in the Bike object type in which we will store the Person objects.

We can do anything with user-defined object types in JavaScript.

Using the Object.create method

If you do not want to get into the trouble of defining a constructor method to define a user-defined object type, you can use the Object.create() method to create an object of any prototype object which is already defined.

Let’s take an example to understand this.

let Bike = {
    company: 'KTM',  // Default value of properties
    model: 'Duke 390',
    show: function() {  // Method to display property type of Bike
        document.write(this.company+" "+this.model);
    }
};

// using Object.create to create a new object
let newBike = Object.create(Bike);
newBike.company = 'Yamaha';
newBike.model = 'R15';
newBike.show();

Yamaha R15

As you can see in the code above, we can use the Object.create method to create a new object using an already defined object, and then if required we can change the properties values and use the object function too.

JavaScript Objects

In JavaScript, we can define an object as a collection of properties that are defined as a key-value pair, where the key is the generic name of the object feature which can be assigned a value. Don’t confuse this object with class objects, where we define a class and then create an object for it.

In JavaScript, an object is a standalone entity where the properties of the object define the characteristics of the object.

For example, if we consider a mobile phone as an object then its properties are its color, screen size, brand name, operating system, RAM, Memory, etc. All these properties define the characteristics of a mobile phone.

The property of an object is a key:value pair, where key refers to a variable, and value refers to any type of value associated with the key. The value can be of any type like a number, string, or even an array, or another object.

We can create an object in JavaScript either by using the constructor function or the object literal.

Creating a JavaScript Object

We can create a JavaScript object either by using the Object constructor or using the object literal syntax. Below we have the basic syntax for creating an object is JavaScript using both ways:

/* Using Object constructor */
let obj1 = new Object();
/* Using the object literal syntax - empty object */
let obj2 = {};
/* Using the object literal syntax - with properties */
let obj3 = { key1:value1, key2:value2, ...};

When we create an object using the Object constructor, we first create an empty object and then assign properties to it while in case of the object literal syntax, we can create an empty object or specify properties within the curly braces while creating an object.

No need to get confused, JavaScript provides with multiple different ways for creating objects. Let’s take a few examples to cover different ways of creating objects in JavaScript.

JavaScript Object Using Object Constructor

We can create a direct instance of an object by using the new keyword:

let mobile = new Object();

and then can assign properties to it using the dot operator(.) as shown below:

mobile.name = 'Blackberry';
mobile.color = 'Black';
mobile.price = 40000;

We can also create the object and assign properties to it in a single go like this,

let mobile = new Object(),
             color = 'Black',
             price = 40000,
             specifications = new Object();

As you can see in the code example above, our object has a property which is also an object.

JavaScript Object Using Object Literal Syntax

To create an object using object literal syntax, we use curly brackets { }. It is the preferred way and simpler way too, but do the same as Object constructor. We can define properties of this object inside the curly brackets.

Let’s create an object, mobile phone that has colornameprice as its properties.

let mobile = {         
    name: "Apple iPhone",
    color: "Black",
    price: 100000      
};

In the mobile object, there are three properties:

  1. The first property has the key name and the value “Apple iPhone“.
  2. The second one has the key color and the value “Black“.
  3. The third property has key price and the value 100000.

Accessing JavaScript Object Property

To get the property of an object, we can use the dot(.) operator followed by the property name or key. See the below example,

<!doctype html>
	<head>
		<title>JS Accessing Object Property</title>
	</head>
	<body>
		<!-- HTML body -->
		<script>
			/* JS comes here */
            let mobile = {         
                name: "Samsung",
                color: "black",
                price: 40000      
            };

            // Accessing property
            document.write(mobile.name);
            document.write("<br>"+mobile.color);
		</script>
	</body>
</html>

It doesn’t matter how you create the object, the way of accessing the property will remain the same.

Using Square Bracket Notation:

We can also use the square bracket notation for accessing any property using the property name or key. A JavaScript object is similar to an associative array, because an associative array also has named index value unlike the numeric index values in a simple array.

Let’s take an example to see how we can use the square bracket notation to access object properties:

/* JS comes here */
let mobile = {         
    name: "Samsung",
    color: "black",
    price: 40000      
};

// Accessing property using square brackets
document.write(mobile['name']);
document.write("<br>"+mobile['color']);

Just like we access a property value, we can also add a new property to an object.

Add new Property to JavaScript Object

JavaScript allows us to add a new property to an existing object. See the below example:

let mobile = {         // an object
  name: "BlackBerry",  // property
  color: "black",
  price: 40000      
};


// Adding New Property
mobile.weight = "100gm"

// Accessing newly added property
document.write(mobile.weight)

100gm

Using Square Bracket Notation:

We can also use the square bracket notation for setting any property using the property name or key.

Let’s take an example to see how we can use the square bracket notation to access object properties:

/* JS comes here */
let mobile = {         
    name: "Samsung",
    color: "black",
    price: 40000      
};

// setting property using square brackets
mobile['screen'] = "5 in";

Remove Property of a JavaScript Object

If we want to remove any property from the object, then we can do it easily by using deleteoperator. See the below example:

let mobile = {         // an object
  name: "BlackBerry",  // property
  color: "black",
  price: 40000      
};


// Deleting Property
delete mobile.price;

// Trying to access deleted property
document.write(mobile.price);   // Undefined

Undefined

Update Property of a JavaScript Object

Updating a JavaScript object property value with a new one is allowed. To update any property, just assign it a new value. See the below example:

let mobile = {         // an object
  name: "BlackBerry",  // property
  color: "black",
  price: 40000 
};


// Updating property 
mobile.color = "Pearl White";

// Accessing Property
document.write(mobile.color);

Pearl White

JavaScript Object: Handling Multiword Property

JavaScript allows us to create multiword property but with little care because accessing multiword property using dot(.) operator will produce a syntax error. So, to avoid this error, we should use square brackets ([]).

Let’s take an example to see this:

let mobile = {         // an object
  name: "BlackBerry",  // property
  color: "black",
  "latest price": 40000      // multiword should enclose with double quotes
};

// setting multiword property key-value with square brackets
mobile["screen size"] = "5 in";


// Accessing Property using square brackets
document.write(mobile["latest price"]);

40000

If we will try to access a multiword key property using the dot operator (.) we will get a syntax error.

Traversing JavaScript Object

We can traverse the object’s properties by using for-in loop. It returns keys associated with object that further can be used to fetch values. See the below example:

let mobile = {         // an object
  name: "BlackBerry",  // property
  color: "black",
  price: 40000
};


// Traversing object
for (key in mobile) {
	document.write(mobile[key]+"<br>")
}

BlackBerry black 40000

Creating Method in JavaScript Object

We can also define methods in an object. A method is a function associated with an object. Methods are defined just as normal JavaScript functions are defined, except that they have to be assigned to an object as a property.

Defining the JavaScript Object Method:

Here, we are defining a method showInfothat will display the information about the object, i.e. all the object properties.

let mobile = {         // an object
    name: "BlackBerry",  // property
    color: "black",
    price: 40000

    // defining method
    showInfo: function() {
        document.write(this.name+" "this.color+" "+this.price);
    }
};

Accessing the JavaScript Object Method:

Accessing or calling a method is pretty easy, just use dot(.) operator with object name:

var mobile = {         // an object
    name: "BlackBerry",  // property
    color: "black",
    price: 40000,

    // method
    showInfo: function() {
        document.write(this.name+" "+this.color+" "+this.price)
    },
};

// Calling method
mobile.showInfo();

BlackBerry black 40000

JavaScript Built-in Objects

JavaScript has rich set of built-in objects that can be used to deal with various types of collections. Some commonly used built-in types are listed below.

  1. String
  2. RegExp
  3. Boolean
  4. Number
  5. Array
  6. Math
  7. Date

In the next few tutorials, we will cover the built-in JavaScript objects and we will also learn how we can create custom user-defined objects in JaavaScript.