Friday, June 30, 2017

Laravel 5: Change Default Database connection Dynamically | Change database name of connection on the fly | How to change default database connection in controller | Multiple DB Connections | Specifying DB connection information dynamically instead of config key | How to Use Multiple Database Connections in Laravel Application

use Illuminate\Config\Repository;

public function __construct(Repository $config) {}


So now you can $config from the above reference.

Below is a sample usage of change database name:

$config->set("database.connections.mysql.database", "test");

or

app()->config->set("database.connections.mysql.database", "test");

You can use this functionality in middle-ware.

If your app already connected then you have to disconnect it before make new connection available.

Below follow steps to disconnect connection:

$dm = app("Illuminate\\Database\\DatabaseManager");

$dm->disconnect();

Laravel 5: How to set and get config variable in Controller | Use of Application Config in Controller

use Illuminate\Contracts\Foundation\Application;
use Illuminate\Config\Repository;

public function __construct(Application $app, Repository $config) {}

So now you can $app and $config from the above reference.

Below is a sample usage of $config:

$config->set("database.connections.mysql.database", "test");

How to select two additional columns from another table based on values in the base table

Below is sample SQL showing how we can use additional columns from another table based on value of base table.


SELECT base_table.id, another_table.id AS some_other_name, another_table.name
FROM base_table AS base_table
  INNER JOIN (SELECT id, name FROM another_table) another_table
    ON base_table.another_table_id = another_table.id
WHERE another_table.some_reference = 15
ORDER BY base_table.id DESC
LIMIT 10


Laravel 5: Fluent Query Builder Join with subquery

Laravel is a strong php based framework today. Below is a code sample showing how raw query used for join.

$list = DB::table("users AS u")
    ->join(DB::raw('(SELECT id AS oid,name FROM organization) o'), function($join) {
        $join->on('o.oid', '=', 'u.organization_id');
    })
    ->where("o.oid", 15)
    ->limit(10)
    ->orderBy("u.id", "DESC")
    ->select("u.id", "o.oid", "o.name")
    ->get();


Thursday, June 29, 2017

How create json format with group-concat mysql | How to put JSON into a column data if sub-query returns more than 1 row in MySQL | Optimized way of getting subqueries at once using JSON

How create json format with group-concat mysql |  How to put JSON into a column data if sub-query returns more than 1 row in MySQL | Optimized way of getting subqueries at once using JSON.

A bit convoluted, but you could create JSON objects for each row, concatenate them using GROUP_CONCAT and cast the result (wrapped in [] to make it an array) to JSON;

Below is the full example:


<?php
define("DB_DEFAULT_HOST", "localhost");
define("DB_DEFAULT_DATABASE", "test71");
define("DB_DEFAULT_USER", "root");
define("DB_DEFAULT_PASSWORD", "");

$dbh = null;
try {
    $dbh = new PDO(
        "mysql:host=" . DB_DEFAULT_HOST . ";dbname=" . DB_DEFAULT_DATABASE,
        DB_DEFAULT_USER,
        DB_DEFAULT_PASSWORD
    );
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbh->beginTransaction();

    $query =
        "SELECT
            s.name AS Name, s.roll AS Roll,
            CONCAT(
              '[', COALESCE(
                GROUP_CONCAT(
                  CONCAT('{', 
                    '\"ExamName\":', '\"', HEX(CONVERT(e.subject USING utf32)), '\"',
                    ',\"Score\":', '\"', e.score, '\"',
                  '}')
                  SEPARATOR ','
                ), ''
              ), ']'
            ) AS ExamsRaw
        
        FROM student AS s
          LEFT JOIN exams AS e ON e.student_id=s.id
        
        GROUP BY s.id";

    $students = $dbh->query($query)->fetchAll(PDO::FETCH_OBJ);
    foreach ($students as $entity) {
        $entity->Exams = array();
        foreach (json_decode($entity->ExamsRaw) as $group) {
            $group->ExamName = hexToStr($group->ExamName);
            array_push($entity->Exams, $group);
        }
        unset($entity->ExamsRaw);
    }
    echo "<pre>";
    print_r($students);
    echo "</pre>";
}
catch (\Exception $ex) {
    echo "MySQL_Error=" . $ex->getMessage();
    $dbh->rollBack();
}

function hexToStr($hex)
{
    $string = '';
    for ($index = 0; $index < strlen($hex) - 1; $index += 2) {
        $string .= chr(hexdec($hex[$index] . $hex[$index + 1]));
    }
    return $string;
}

And below is the output of above example code block:


Array
(
    [0] => stdClass Object
        (
            [Name] => Prtiom First Year
            [Roll] => P1
            [Exams] => Array
                (
                    [0] => stdClass Object
                        (
                            [ExamName] => ©|æ|þ|½|±|®|¶
                            [Score] => 1.12
                        )

                    [1] => stdClass Object
                        (
                            [ExamName] => Subject 2   
                            [Score] => 2.54
                        )

                    [2] => stdClass Object
                        (
                            [ExamName] =>  ¡¢£¤¥¦§¨©
                            [Score] => 1.98
                        )

                )

        )

    [1] => stdClass Object
        (
            [Name] => Pritom Second Year
            [Roll] => P2
            [Exams] => Array
                (
                    [0] => stdClass Object
                        (
                            [ExamName] => Subject 2
                            [Score] => 4.00
                        )

                    [1] => stdClass Object
                        (
                            [ExamName] => Subject 3
                            [Score] => 3.00
                        )

                )

        )

)

Aware that mysql group function max length is by default 1024 characters. If your group function more than 1024 then you have to change limit of mysql group function using following query:

This is for current session:
SET SESSION group_concat_max_len = 1000000;

But if you want it global scope, then do following:
SET GLOBAL group_concat_max_len = 1000000;

Tuesday, June 27, 2017

Laravel 5: How to modify Request values | How to "artificially" add values to Request array | How to dynamically add params to Request array

Laravel 5: How to modify Request values | How to "artificially" add values to Request array | How to dynamically add params to Request array. You can use the merge() method on the $request object. In spite of the methods name, it actually replaces any values associated with the member names specified by the keys of the parameter rather than concatenating their values or anything like that. 

A few times I encountered a situation – a store() or update() method with Request parameter, but I needed to add some additional value to the request before calling Eloquent functions. So how to do that? Apparently, pretty easy.

use Illuminate\Http\Request;

protected $request;

public function __construct(Request $request)
{
    $this->request = $request;

}

$this->request->merge(["custom" => "New Custom Value"]);






..

Monday, June 26, 2017

Validating a URL in PHP

Check if the variable $url is a valid URL:

The FILTER_VALIDATE_URL filter validates a URL.

Possible  flags:

FILTER_FLAG_SCHEME_REQUIRED - URL must be RFC compliant.
Like http://example

FILTER_FLAG_HOST_REQUIRED - URL must include host name.
Like http://www.example.com

FILTER_FLAG_PATH_REQUIRED - URL must have a path after domain.
Like www.example.com/example1/

FILTER_FLAG_QUERY_REQUIRED - URL must have a query string.
Like "example.php?name=Peter&age=37"

filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED)
filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)
filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)
filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_QUERY_REQUIRED)


Set floating div to height: 100% | Div as Table | Responsive Table | Table Table-Row Table-Cell | Table Div

lefttttttttttttttttttttttttt
middleeeeeeeeeeeeeeeeeeeeeee
rightttttttttttttttttttttttt

You could do it by setting up a table-like structure of <div> elements in your HTML and then using display: "table", "table-row" and "table-cell". This will work because table cells in the same row automatically resize to the same height as the tallest cell. However, IE7 will not support table properties.

<div id="table">
    <div id="table-tr">
        <div id="table-td">
            lefttttttttttttttttttttttttt
        </div>
        <div id="table-td">
            middleeeeeeeeeeeeeeeeeeeeeee
        </div>
        <div id="table-td">
            rightttttttttttttttttttttttt
        </div>
    </div>
</div>

<style type="text/css">
#table {
    background-color: red;
    width: 300px;
    height: 120px;
    overflow: auto;
    padding: 1px;
    display: table;
    table-layout:fixed;
}

#table-tr {
    display: table-row;
}

#table-td {
    width: 33.34%;
    display: table-cell;
    background-color: #ccc;
    border: 1px solid red;
    word-wrap: break-word;
    padding: 3px;
}
</style>

Sunday, June 25, 2017

PHP Class for HTTP Response Status Codes

HTTP Response Status Codes:

<?php
class HttpStatusCodeUtils
{
    // [Informational 1xx]
    const HTTP_CONTINUE = 100;
    const HTTP_SWITCHING_PROTOCOLS = 101;
    // [Successful 2xx]
    const HTTP_OK = 200;
    const HTTP_CREATED = 201;
    const HTTP_ACCEPTED = 202;
    const HTTP_NONAUTHORITATIVE_INFORMATION = 203;
    const HTTP_NO_CONTENT = 204;
    const HTTP_RESET_CONTENT = 205;
    const HTTP_PARTIAL_CONTENT = 206;
    // [Redirection 3xx]
    const HTTP_MULTIPLE_CHOICES = 300;
    const HTTP_MOVED_PERMANENTLY = 301;
    const HTTP_FOUND = 302;
    const HTTP_SEE_OTHER = 303;
    const HTTP_NOT_MODIFIED = 304;
    const HTTP_USE_PROXY = 305;
    const HTTP_UNUSED = 306;
    const HTTP_TEMPORARY_REDIRECT = 307;
    // [Client Error 4xx]
    const HTTP_BAD_REQUEST = 400;
    const HTTP_UNAUTHORIZED = 401;
    const HTTP_PAYMENT_REQUIRED = 402;
    const HTTP_FORBIDDEN = 403;
    const HTTP_NOT_FOUND = 404;
    const HTTP_METHOD_NOT_ALLOWED = 405;
    const HTTP_NOT_ACCEPTABLE = 406;
    const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
    const HTTP_REQUEST_TIMEOUT = 408;
    const HTTP_CONFLICT = 409;
    const HTTP_GONE = 410;
    const HTTP_LENGTH_REQUIRED = 411;
    const HTTP_PRECONDITION_FAILED = 412;
    const HTTP_REQUEST_ENTITY_TOO_LARGE = 413;
    const HTTP_REQUEST_URI_TOO_LONG = 414;
    const HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
    const HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    const HTTP_EXPECTATION_FAILED = 417;
    // [Server Error 5xx]
    const HTTP_INTERNAL_SERVER_ERROR = 500;
    const HTTP_NOT_IMPLEMENTED = 501;
    const HTTP_BAD_GATEWAY = 502;
    const HTTP_SERVICE_UNAVAILABLE = 503;
    const HTTP_GATEWAY_TIMEOUT = 504;
    const HTTP_VERSION_NOT_SUPPORTED = 505;


    private static $messages = array(
        // [Informational 1xx]
        100 => '100 Continue',
        101 => '101 Switching Protocols',
        // [Successful 2xx]
        200 => '200 OK',
        201 => '201 Created',
        202 => '202 Accepted',
        203 => '203 Non-Authoritative Information',
        204 => '204 No Content',
        205 => '205 Reset Content',
        206 => '206 Partial Content',
        // [Redirection 3xx]
        300 => '300 Multiple Choices',
        301 => '301 Moved Permanently',
        302 => '302 Found',
        303 => '303 See Other',
        304 => '304 Not Modified',
        305 => '305 Use Proxy',
        306 => '306 (Unused)',
        307 => '307 Temporary Redirect',
        // [Client Error 4xx]
        400 => '400 Bad Request',
        401 => '401 Unauthorized',
        402 => '402 Payment Required',
        403 => '403 Forbidden',
        404 => '404 Not Found',
        405 => '405 Method Not Allowed',
        406 => '406 Not Acceptable',
        407 => '407 Proxy Authentication Required',
        408 => '408 Request Timeout',
        409 => '409 Conflict',
        410 => '410 Gone',
        411 => '411 Length Required',
        412 => '412 Precondition Failed',
        413 => '413 Request Entity Too Large',
        414 => '414 Request-URI Too Long',
        415 => '415 Unsupported Media Type',
        416 => '416 Requested Range Not Satisfiable',
        417 => '417 Expectation Failed',
        // [Server Error 5xx]
        500 => '500 Internal Server Error',
        501 => '501 Not Implemented',
        502 => '502 Bad Gateway',
        503 => '503 Service Unavailable',
        504 => '504 Gateway Timeout',
        505 => '505 HTTP Version Not Supported'
    );


    public static function httpHeaderFor($code)
    {
        return 'HTTP/1.1 ' . self::$messages[$code];
    }


    static function getMessageForCode($code)
    {
        return isset(self::$messages[$code]) ? self::$messages[$code] : "$code Invalid Request";
    }

    static function isError($code)
    {
        return is_numeric($code) && $code >= self::HTTP_BAD_REQUEST;
    }

    static function canHaveBody($code)
    {
        return
            // True if not in 100s
            ($code < self::HTTP_CONTINUE || $code >= self::HTTP_OK)
            && // and not 204 NO CONTENT
            $code != self::HTTP_NO_CONTENT
            && // and not 304 NOT MODIFIED
            $code != self::HTTP_NOT_MODIFIED;
    }
}
?>


PHP: Import variables into the current symbol table from an array

PHP: Import variables into the current symbol table from an array

$params = array("x1" => "VALUE OF X1");
extract($params);
echo (isset($x1) ? "X1=".$x1 : "NO X1 DEFINED") . "<BR>";
echo (isset($x2) ? "X2=".$x2 : "NO X2 DEFINED") . "<BR>";

And output would be following:

X1=VALUE OF X1
NO X2 DEFINED


Laravel 5: Generate a URL to a controller action

It's easy to generate a URL as like Controller Action. Suppose you have a controller named "UserController" and have an action inside the Controller named "customerLogin" and in routes.php you mentioned the router as: 

"Route::get("login_customer", "UserController@customerLogin"

So when you browse www.domain.com/login_customer then actually executed "customerLogin" action of "UserController".

Now for some reason you need to construct a URL based on Controller and Action, then you can apply below to generate URL:

action('UserController@customerLogin', ['id' => "3 0"])

Will generate below URL:

www.domain.com/login_customer?id=3+0

If you Controller exists inside another folder then you ca

action('Folder\UserController@customerLogin', ['id' => "3 0"])


Laravel 5: Use of Laravel Middleware WEB | API | THROTTLE

You have to create a middleware first. Create a php file named "ApiFilter.php" in "app/Http/Middleware" folder with following contents:


<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request as HttpRequest;

class ApiFilter
{
    protected $auth;

    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    public function handle(HttpRequest $request, Closure $closure)
    {
        if ($this->auth->guest()) {
            if ($request->ajax()) {
                return response('Unauthorized.', 401);
            }
            else {
                return redirect()->guest('login');
            }
        }
        return $closure($request);
    }
}


Now you have to register this middleware to your project. Need to open "App\Http\Kernel.php" file. If you want to register this middleware for global scope then you have to add the below line as follows:


protected $middleware = [
    \App\Http\Middleware\ApiFilter::class
];


So when you browse any url in your project scope, this middleware can handle them.

But if you want to the middleware for specific area you have to add the middleware to "$middlewareGroups" as follows:


protected $middlewareGroups = [
    'web' => [
        .....
    ],

    'api' => [
        'throttle:3,1',
        \App\Http\Middleware\ApiFilter::class
    ],
];


Now add the following lines to "app\Http\routes.php":


Route::group(["middleware" => "api", "prefix" => "api"], function() {
    Route::get('action_name', 'ApiController@action_name');
});


If you browse "www.domain.com/api/action_name" it will pass through ApiFilter middleware bacause of prefix "api" used. But if you only browse "www.domain.com/action_name" it will pass through another middleware.



These middleware may be assigned to groups or used individually


protected $routeMiddleware = [
    'my_middleware' => \App\Http\Middleware\Authenticate::class
];

And can be used as below:

Route::group(['middleware' => 'my_middleware'], function() {
    Route::get('landing-page', 'MyController@landingPage');
});


We can use "throttle" which will restrict request overloading. Here we used "throttle:3,1" means per minute 3 request can be granted, if more request send request rejected as below image:

We need to add below line to "routeMiddleware" for "throttle" action:


protected $routeMiddleware = [
    .........,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];




Laravel 5: How to Select from Sub-query using Laravel Query Builder

Laravel 5: How to Select from Sub-query using Laravel Query Builder. It's very easy to use Sub-Query as Select query in Laravel. Below is a sample code snippet:



$query = DB::table("employee")->whereIn("id", array(1, 2, 3, 4));
$result = DB::table(DB::raw("(" . $query->toSql() . ") as res"))
    ->mergeBindings($query)
    ->whereIn("res.id", array(2, 3))->get();

Which will generate below SQL:

select * from (select * from `employee` where `id` in (1, 2, 3, 4)) as res 
where `res`.`id` in (2, 3))

Friday, June 23, 2017

Laravel 5.X: How Do I Get Raw SQL Query As String With Binders From Query Builder | Query Builder To Raw SQL

Laravel 5.X: How Do I Get Raw SQL Query As String With Binders From Query Builder. Its very easy and now few steps from here. It's interesting.


use Illuminate\Support\Facades\DB;

$model = DB::table('employee')
    ->where("employee.id", "<>", 0)
    ->whereIn("employee.id", array(1, 2))
    ->where("employee.type", "PERMANENT")
    ->where(function ($q) {
        $q->where("employee.id", 1)->orWhere("employee.id", 2);
    })
    ->limit(10)->offset(0)
    ->groupBy("employee.id")
    ->select("employee.id");

$replace = function ($sql, $bindings) {
    $pos = 0;
    $needle = '?';
    foreach ($bindings as $replace) {
        if (is_string($replace)) {
            $replace = DB::connection()->getPdo()->quote($replace);
        }
        $pos = strpos($sql, $needle, $pos);
        if ($pos !== false) {
            $sql = substr_replace($sql, $replace, $pos, strlen($needle));
            $pos = $pos + strlen($replace);
        }
    }
    return $sql;
};

$sql = $replace($model->toSql(), $model->getBindings());
echo "SQL=" . $sql;

And output would be like below:

SELECT `employee`.`id`
FROM `employee`
WHERE `employee`.`id` <> 0 AND `employee`.`id` IN (1, 2) AND
      `employee`.`type` = 'PERMANENT' AND (`employee`.`id` = 1 OR `employee`.`id` = 2)
GROUP BY `employee`.`id`
LIMIT 10 OFFSET 0

Laravel 5.X: Use of SubQuery | Sub Query in Where Condition

Laravel 5.X: Use of Sub-query | Sub Query in Where Condition. It's very important. Below is an sample example how we can use sub-query in our application.



$test_data = Employee::from((new Employee())->getTable() . " AS entity")

OR

$test_data = DB::table((new Employee())->getTable() . " AS entity")
    ->whereIn("entity.id", function($q) {
        $q->select("entity.id");
        $q->from((new Employee())->getTable() . " AS entity");
        $q->join((new Supervisor())->getTable() . " AS user", "user.id", "=", "entity.sup_id");
        $q->whereNotNull("entity.sup_id");
        $q->where("user.first_name", "like", "%E%");
    })
    ->select("entity.id", "entity.type")
    ->limit(5)
    ->get();


And will generate below SQL:


SELECT
  `entity`.`id`,
  `entity`.`type`
FROM `employee` AS `entity`
WHERE `entity`.`id` IN (
  SELECT `entity`.`id`
  FROM `employee` AS `entity` INNER JOIN `users` AS `user` ON `user`.`id` = `entity`.`sup_id`
  WHERE `entity`.`sup_id` IS NOT NULL AND `user`.`first_name` LIKE '%E%'
)
LIMIT 5

Responsive CSS: Responsive Table Data Representation

We can easily display our tables in table view for normal browser and list view for mobile device easily. Below is a code snippet:



<meta name="viewport" content="width=device-width, initial-scale=1"/>
<style type="text/css">
    .responsive {
        width: 100%;
        font-size: 18px;
    }
    .responsive thead td {
        padding: 7px;
        background-color: #8b91a2;
    }
    .responsive tbody td {
        padding: 7px;
    }
    .responsive .visible-xs {
        display: none;
    }
    @media screen and (min-width: 0px) and (max-width: 768px) {
        .responsive td {
            font-size: 18px;
        }
        .responsive .hidden-xs {
            display: none !important;
        }
        .responsive .visible-xs {
            display: table-row !important;
        }
        .responsive tbody td {
            display: block;
            width: 100%;
            border: 0 !important;
            box-sizing: border-box !important;
            padding: 0 10px !important;
            font-size: 24px;
        }
        .responsive .separator {
            display: inline-block !important;
            background-color: moccasin;
            width: 100%;
            height: 7px
        }
    }
</style>
<table class="responsive">
    <thead>
    <tr class="hidden-xs">
        <td>NAME</td>
        <td>ROLL</td>
        <td>STATUS</td>
        <td>GPA</td>
    </tr>
    </thead>
    <tbody>
    <tr><td class="visible-xs separator" colspan="4"><div>&nbsp;</div></td></tr>
    <tr>
        <td><span class="visible-xs">NAME:</span>Pritom</td>
        <td><span class="visible-xs">ROLL:</span>00303</td>
        <td><span class="visible-xs">STATUS:</span>PASSED</td>
        <td><span class="visible-xs">GPA:</span>4.50</td>
    </tr>
    <tr><td class="visible-xs separator" colspan="4"><div>&nbsp;</div></td></tr>
    <tr>
        <td><span class="visible-xs">NAME:</span>Pritom</td>
        <td><span class="visible-xs">ROLL:</span>00304</td>
        <td><span class="visible-xs">STATUS:</span>PASSED</td>
        <td><span class="visible-xs">GPA:</span>4.51</td>
    </tr>
    <tr><td class="visible-xs separator" colspan="4"><div>&nbsp;</div></td></tr>
    <tr>
        <td><span class="visible-xs">NAME:</span>Pritom</td>
        <td><span class="visible-xs">ROLL:</span>00305</td>
        <td><span class="visible-xs">STATUS:</span>PASSED</td>
        <td><span class="visible-xs">GPA:</span>4.52</td>
    </tr>
    <tr><td class="visible-xs separator" colspan="4"><div>&nbsp;</div></td></tr>
    <tr>
        <td><span class="visible-xs">NAME:</span>Pritom</td>
        <td><span class="visible-xs">ROLL:</span>00306</td>
        <td><span class="visible-xs">STATUS:</span>PASSED</td>
        <td><span class="visible-xs">GPA:</span>4.53</td>
    </tr>
    <tr><td class="visible-xs separator" colspan="4"><div>&nbsp;</div></td></tr>
    <tr>
        <td><span class="visible-xs">NAME:</span>Pritom</td>
        <td><span class="visible-xs">ROLL:</span>00307</td>
        <td><span class="visible-xs">STATUS:</span>PASSED</td>
        <td><span class="visible-xs">GPA:</span>4.54</td>
    </tr>
    <tr><td class="visible-xs separator" colspan="4"><div>&nbsp;</div></td></tr>
    <tr>
        <td><span class="visible-xs">NAME:</span>Pritom</td>
        <td><span class="visible-xs">ROLL:</span>00308</td>
        <td><span class="visible-xs">STATUS:</span>PASSED</td>
        <td><span class="visible-xs">GPA:</span>4.55</td>
    </tr>
    <tr><td class="visible-xs separator" colspan="4"><div>&nbsp;</div></td></tr>
    </tbody>
</table>




Thursday, June 22, 2017

Laravel 5:Redirect back to the same page where the request comes from with input and messages

In your controller:

use Illuminate\Support\Facades\Redirect;

$error[] = "SOME ERRORS";
return Redirect::back()
    ->withErrors(compact('error'))
    ->with("reason1", "SOME REASON 1")
    ->with("reason2", "SOME REASON 2")
    ->withInput();


And in your view file:

<div>Reason1: {{ session('reason1') }}</div>

<div>Reason1: {{ session('reason2') }}</div>

Option "withInput" will fill back up input fields with previous data:

{!! Form::label('name', 'Name:') !!}

Wednesday, June 21, 2017

MySQL Update Table Using Join Of Other Tables | MySQL Join Table On Update

UPDATE table1 AS t1 LEFT JOIN table2 AS t2 ON (t1.t2_id = t2.id)
SET t1.some_field = t1.some_field + 1 
WHERE t1.id in (1,2,3) AND t2.some_field = "SOME MATCH VALUE"

JavaScript | jQuery: Manual Ajax Form Submit Using XMLHttpRequest | XMLHttpRequest to Post HTML Form | Upload File Ajax | Submit FormData

It's easy to submit an form using JavaScript ajax request. We also can upload files using ajax form submit. Below is a simple code snippet:


<form name="content_info">
    <input type="file" name="file"/>
    <button type="button" onclick="doPost()">Ajax Submit</button>
</form>

<script type="text/javascript">
    function doPost() {
        var form = document.forms.namedItem("content_info");
        var formData = new FormData(form);
        //or formData = new FormData();
        formData.append("custom_param", "custom_param_value");

        var request = new XMLHttpRequest();
        request.open("POST", "submit.php", true);
        request.responseType = "json";
        request.onload = function(oEvent) {
            console.log(request.status);
            console.log(request);
            console.log(request.response);
            alert(request.status);
        };
        request.onerror = function (error) {
            console.log(error);
        };
        request.setRequestHeader("Custom-Code", "EKKODJIU");
        request.send(formData);
    }
</script>