Show queries in laravel

 

Laravel provides a database query builder. To see the query use toSql() in laravel.

 

$result = DB::table(‘users’)
->where(‘username’, ‘like’, ‘%admin%’)
->toSql() // to see the query which is executed
//  ->get()->toArray();  to get results
dd($result)

Laravel update record

Use Query Builder to update records, This is a sample:

DB::table('post')
->where('id', $id)
->update(['status' => "0"]);

Or Use another method to load DB 
$post = Post::find($id);
$post->status = "0";
$post->save();

generate random number in php

To generate 6 digit random number code in php.

Following function will help you to generate random number.

<?php
function _generate_code(){
$character_set_array = array();
$character_set_array[] = array(‘count’ => 3, ‘characters’ => ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’);
$character_set_array[] = array(‘count’ => 3, ‘characters’ => ‘0123456789’);
$temp_array = array();
foreach ($character_set_array as $character_set) {
for ($i = 0; $i < $character_set[‘count’]; $i++) {
$temp_array[] = $character_set[‘characters’][rand(0, strlen($character_set[‘characters’]) – 1)];
}
}
shuffle($temp_array);
return implode(”, $temp_array);
}

echo _generate_code();

What is friend function?

friend function

– Friend function is a friend of a class.
– It is allowed to access Public, private or protected data of that class.
– It can be declared anywhere in the class declaration
– It doesn’t have any effect of access control keywords like private, public or protected.

PHP cookies

PHP cookies
Cookies are text files stored on the client computer and they are kept of use tracking purpose. We can create and retrieve the cookie in php

Create Cookies With PHP

A cookie is created with the setcookie() function.After setting the cookies, they can be used when the next page is loaded by using $_COOKIE.
For each cookie this function has to be called separately.

Function to set cookie
Setcookie(name, value, expire, path, domain);

Here is the detail of all the arguments −

Name − This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies.

Value − This sets the value of the named variable and is the content that you actually want to store.

Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed.

Path − This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories.

Domain − This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them.

Security − This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.

Example:
$cookie_name = “user”;
$cookie_value = “Test name”;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), “/set folder”);

Retrieving cookie value:

The cookie that is set can be retrieved as shown below:
Echo $_cookie[“user”];

You can check with cookie is st or not with Isset() function.

Switch case in PHP

The switch-case statement is an alternative to the if-elseif-else statement, which does almost the same thing. The switch-case statement tests a variable against a series of values until it finds a match, and then executes the block of code corresponding to that match.
switch(value)
case condition1:
break;
case condition2:
break

Below is example to display a different message for each month.
Example »

<?php

$today = date(“m”);

switch($month){

case “01”:

echo “Current month  is January.”;

break;

case “02”:

echo “Current month  is February.”;

break;

case “03”:

echo “Current month  is March.”;

break;

…….

default:

echo “It will return if case dows not exits.”;

break;

}

?>

Use break to prevent the code from running into the next case automatically

GET and POST Methos in PHP

Methods of Sending Information to Server

A web browser communicates with the server typically using one of the two HTTP (Hypertext Transfer Protocol) methods — GET and POST. Both methods pass the information differently and have different advantages and disadvantages, as described below.
The GET Method

In GET method the data is sent as URL parameters that are usually strings of name and value pairs separated by ampersands (&). In general, a URL with GET data will look like this:
http://www.example.com/test.php?action=del&id=1

Advantages and Disadvantages of Using the GET Method

Data sent by the GET method are displayed in the URL, it is possible to bookmark the page with specific query string values.
The GET method is not suitable for passing sensitive information such as the username and password, because these are fully visible in the URL query string.
Because the GET method assigns data to a server environment variable, the length of the URL is limited. So, there is a limitation for the total data to be sent.

<?php

if(isset($_GET[“name”])){

echo “This GET example Name:, ” . $_GET[“name”] ;

}

?>

<form method=”get” action=”<?php echo $_SERVER[“PHP_SELF”];?>”>

<label for=”inputName”>Name:</label>

<input type=”text” name=”name”>

<input type=”submit” value=”Submit”>

</form>

The POST Method

In POST method the data is sent to the server. Data sent through POST method will not visible in the URL.
It is more secure than GET because user-entered information is never visible in the URL query string or in the server logs.
There is a much larger limit on the amount of data that can be passed and one can send text data as well as binary data (uploading a file) using POST.

PHP provide another superglobal variable $_POST to access all the information sent via post method or submitted through an HTML form using the method=”post”.

<?php

if(isset($_POST[“name”])){

echo “This post example Name:, ” . $_POST[“name”];

}

?>

<form method=”post” >

<label for=”inputName”>Name:</label>

<input type=”text” name=”name” >

<input type=”submit” value=”Submit”>

</form>

$_REQUEST
PHP provides another superglobal variable $_REQUEST that contains the values of both the $_GET and $_POST

<?php

if(isset($_REQUEST[“name”])){

echo “This post example Name:” . $_REQUEST[“name”];

}

?>

<form method=”post” >

<label for=”inputName”>Name:</label>

<input type=”text” name=”name” >

<input type=”submit” value=”Submit”>

</form>

PHP display current server path

We can use getcwd it will  give you the base path:

<?php
echo getcwd();
?>

  1. To get your current working directory: getcwd()
  2. To get the document root directory: $_SERVER['DOCUMENT_ROOT']
  3. To get the filename of the current script: $_SERVER['SCRIPT_FILENAME']

What are the ways to prevent SQL injection for a CodeIgniter based website?

To prevent SQL injections in PHP, we usually use mysql_real_escape_string() function in mysql queries

In CI there are three methods to prevent SQL injections
1) Escaping Queries
2) Query Binding
3) Active Record Class

Preventing SQL injection in Codeigniter using Escaping Query Method

Example:
input->post(‘name’);
$sql = ‘SELECT * FROM product WHERE product_name=’.$this->db->escape($name);
$this->db->query($sql ;
?>

Here $this->db->escape() determines the data type so that it can escape only string data.

Preventing SQL injection in CI using Query Binding Method
db->query($sql, array(‘active’, ‘mobile’));
?>
In Query Binding Method, you don’t have to escape the values manually as it will automatically do that for you.

Preventing SQL injection in Codeigniter using Active Record Class

Using Active Records, query syntax is generated by each database adapter. It also allows for safer queries, since the values are escaped automatically by the system.
db->get_where(‘product’,array(‘status’ => ‘active’,’sellerId’ => ’10’));
?>