PHP MySQL Order By

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

  • mysqli_query()
  • PDO::__query()

The order by clause is used to fetch data in ascending order or descending order on the basis of column.

Let’s see the query to select data from emp4 table in ascending order on the basis of name column.

  1. SELECT * FROM emp4 order by name  

Let’s see the query to select data from emp4 table in descending order on the basis of name column.

  1. SELECT * FROM emp4 order by name desc  

PHP MySQLi Order by 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 order by name';  
$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 :3 
EMP NAME : jai 
EMP SALARY : 90000 
--------------------------------
EMP ID :2 
EMP NAME : karan 
EMP SALARY : 40000 
--------------------------------
EMP ID :1 
EMP NAME : ratan 
EMP SALARY : 9000 
--------------------------------

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 MySQL Delete Record

PHP mysql_query() function is used to delete 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 Delete 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/>';  
  
$id=2;  
$sql = "delete from emp4 where id=$id";  
if(mysqli_query($conn, $sql)){  
 echo "Record deleted successfully";  
}else{  
echo "Could not deleted record: ". mysqli_error($conn);  
}  
  
mysqli_close($conn);  
?>  

Output:

Connected successfully
Record deleted successfully

PHP MySQL Update Record

PHP mysql_query() function is used to update 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 Update 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/>';  
  
$id=2;  
$name="Rahul";  
$salary=80000;  
$sql = "update emp4 set name=\"$name\", salary=$salary where id=$id";  
if(mysqli_query($conn, $sql)){  
 echo "Record updated successfully";  
}else{  
echo "Could not update record: ". mysqli_error($conn);  
}  
  
mysqli_close($conn);  
?>  

Output:

Connected successfully
Record updated successfully

PHP Delete File

In PHP, we can delete any file using unlink() function. The unlink() function accepts one argument only: file name. It is similar to UNIX C unlink() function.

PHP unlink() generates E_WARNING level error if file is not deleted. It returns TRUE if file is deleted successfully otherwise FALSE.

Syntax

  1. bool unlink ( string $filename [, resource $context ] )  

$filename represents the name of the file to be deleted.

PHP Delete File Example

<?php      
$status=unlink('data.txt');    
if($status){  
echo "File deleted successfully";    
}else{  
echo "Sorry!";    
}  
?>  

Output

File deleted successfully

PHP Cookie

PHP cookie is a small piece of information which is stored at client browser. It is used to recognize the user.

Cookie is created at server side and saved to client browser. Each time when client sends request to the server, cookie is embedded with request. Such way, cookie can be received at the server side.

cookies in php

In short, cookie can be created, sent and received at server end.

Note: PHP Cookie must be used before <html> tag.

PHP setcookie() function

PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you can access it by $_COOKIE superglobal variable.

Syntax

  1. bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path   
  2. [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )  

Example

  1. setcookie(“CookieName”, “CookieValue”);/* defining name and value only*/  
  2. setcookie(“CookieName”, “CookieValue”, time()+1*60*60);//using expiry in 1 hour(1*60*60 seconds or 3600 seconds)  
  3. setcookie(“CookieName”, “CookieValue”, time()+1*60*60, “/mypath/”, “mydomain.com”, 1);  

PHP $_COOKIE

PHP $_COOKIE superglobal variable is used to get cookie.

Example

  1. $value=$_COOKIE[“CookieName”];//returns cookie value  

PHP Cookie Example

<?php  
setcookie("user", "Sonoo");  
?>  
<html>  
<body>  
<?php  
if(!isset($_COOKIE["user"])) {  
    echo "Sorry, cookie is not found!";  
} else {  
    echo "<br/>Cookie Value: " . $_COOKIE["user"];  
}  
?>  
</body>  
</html> 

Output:Sorry, cookie is not found!

Firstly cookie is not set. But, if you refresh the page, you will see cookie is set now.

Output:

Cookie Value: Sonoo

PHP Delete Cookie

If you set the expiration date in past, cookie will be deleted.

<?php  
setcookie ("CookieName", "", time() - 3600);// set the expiration date to one hour ago  
?>  

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.

JavaScript Cookies

JavaScript Cookie is used to store some useful information on the client’s browser which can be accessed in the consecutive HTTP requests.

A cookie is a small file containing information, stored at client’s computer or to be more specific in the client’s browser. Each time when the client requests for a web page, the server refers to the created cookie for information before displaying the requested web page.

Let’s take a simple example to understand the concept of cookies, why its required and how we can use it. Well, if you have a website, which has no user login system, and on your website you have many articles. You want to add a new feature on your website, in which the articles which a user has read will be marked read on the website. But as you do not have a user login system so there is no way that you can save this user related data on your server(Database). In such case, cookies can be used.

We can create a cookie, and store in the client’s browser and in the cookie we can add the URLs(or some other identification) of the articles that the user has already read. When the user again visits any article, we can first check the cookie, if we find the the URL of the current article in the cookie, we can inform the user that you have already read it.

Well, this is how we can use cookies. To store useful information that we can retrieve in further requests to know about the user.

The size of the cookie depends on the browser but generally should not exceed 1K (1,024 bytes). So we should be careful with what all we store in our cookies.

A cookie is generally used to store the user information on a computer so that whenever the user visits the website again, you can know that the user is an old user of yours.

cookie has several attributes, which contain vital information about the cookie such as its name, the domain name to which it belongs and the address of valid path within a domain.

Some commonly used attributes are given below:

1. Cookie Name Attribute

It represents a variable name and the corresponding value to be stored in the cookie.

2. Cookie Expires Attribute

It specifies the time when the cookie will be deleted. It is expressed as a Unix timestamp. In general a cookie is never deleted from the browser, it expires.

3. Cookie Domain Attribute

It represents a domain name(partial or complete) to which the cookie belongs.

For example, if the value for the valid domain attribute is http://www.studytonight.com then the client(browser) will send the cookie information to the web server as part of the HTTP request, every time the user visits the http://www.studytonight.com website.

NOTE: Browser will only provide the cookie which has the domain attribute value same as the current URL in the HTTP request.

4. Cookie Path Attribute

This attribute is used to create path specific cookies for the same domain name. For example, if we want to create a cookie for studytonight.com root path (/) and another cookie for studytonight.com/code/playground to be used in live coding section, then we can use the cookie path attribute to differentiate between the cookies.

It identifies websites based on various paths in the same domain. Setting this attribute to the server root(/) allows the entire domain to access the information stored in the cookie.

5. Cookie Secure Attribute

It restricts a browser from sending cookie information over unsecured connections. If not set, it allows the cookie to be sent over any type of HyperText Transfer Protocol(HTTP) connection.

The default value of the security flag attribute is 0. Setting the value to 1 allow the cookie to be sent over a secure HTTP connection only.

JavaScript Creating and Storing Cookies

In JavaScript, you can create your own cookies to store the user’s information or any information you want.

To create a cookie, use document.cookie property. Set the cookie valuepath to specify where to store cookie and the expiry date to set lifetime of cookie.

Here is the syntax for creating a cookie:

document.cookie = cookieString;

where, the cookieString is a string of form key=value, which will be saved in the cookie. Along with this information, we can provide information like max-age of cookie, expiry time of cookie, path attribute of cookie(its picked up automatically), etc. by separating each key=value pair with semicolon(;).

Here is the syntax for each of the additional optional attribute that you can append to the cookieString to provide more information at the time of cookie creation.

Cookie AttributeDescription
;path=somepathBy default cookie is created for the current URL, but we can change it by providing value for this attribute while creating a cookie.For example:document.write = "username=John Wick;path=/profile";This cookie will be created for the path /profile for the current domain name.
;domain=domainNameThis is again picked up by default as the current domain name. Also, if you try to provide a different domain name than the one on which the JavaScript code is currently loaded the browser will ignore your request.
;max-age=max-age-in-secondsTo specify the time for which the cookie should live or should not expire. It’s value cane be 60*60*24*365 or 31536000 for a year, or 3600 for a day.
;expires=date-in-GMTString-formatThis attribute is used to specify the exact time after which the cookie will expire. If we do not provide this attribute or the max-age attribute then the cookie is expired at the end of the current session for which cookie is created.
;secureTo specify that the cookie should only be provided over secured HTTP connections.For example:document.write = "username=John Wick;secure";
;samesiteThis attribute is used to prevent the browser from sending the cookie data for cross-site requests.

Example Creating Cookies

In the code example below, we have created a cookie with some additional information,

document.cookie = "username=johnwick; expires=Thu, 17 May 2020 10:30:00 IST; path=/";

In the code above, we have created a cookie to store the name of website visitor. As you can see in the code example above, cookie is nothing but a string which has all the information appended, seprated by semicolon(;).

JavaScript Reading Cookies

To read a cookie, we can use document.cookie property. It will return all the stored cookie in the current location path.

var x = document.cookie;

Let’s take a simple example to understand this:

<html>
    <head>
        <title>
            Using onerror Event
        </title>
        <script type="text/javascript">
        document.cookie = "name=johnwick";
        document.cookie = "favorite_car=1969FordMustang";
        function alertCookie() {
            alert(document.cookie);
        }
        </script>
    </head>
    <body>
        <!-- HTML body -->
        <button onclick="alertCookie()">Show cookies</button>
    </body>
</html>

name=johnwick; favorite_car=1969FordMustang

When you will click on the button, you will get the above output in the alert box. So, it’s super easy to store cookies and then read them back.

JavaScript Update Cookie Value

To update the cookie, just set a new value for it and make sure the path should be same, so that it will update the cookie rather than create a new cookie.

document.cookie = "username=BruceWayne; expires=Sat, 15 Aug 2020 12:00:00 UTC; path=/";

It will overwrite the old cookie value.

JavaScript Delete Cookie

To delete a cookie, we need to set a past expiry date for the cookie to delete it immediately, or we can set an expiry date while creating the cookie to specify the time after which the cookie should be deleted.

document.cookie = "username=BruceWayne; expires=Thu, 10 Jan 2020 00:00:00 UTC; path=/;";

You should define the cookie path to ensure that you delete the right cookie.