How to get the last executed query in PHP CodeIgniter?

Are you wanted to get the last executed SQL query in the CodeIgniter project? then, I will help to get the latest query in CodeIgniter

We can get the last executed query using the last_query() function of the inbuilt db class of the CodeIgniter. This function can be used with simple syntax like $this->db->last_query() to see SQL statements of last executed query in PHP CodeIgniter app. You have to simple code that functions after the main query that you wanted to check.

Here is a simple function code which can be added in any controller of the CodeIgniter project and also output for the last query:

Example:

public function check_query_function() {

    $sql = $this->db->get("products");
  
    $query = $this->db->last_query();
   
    echo "<pre>";
    print_r($query);
    exit;
}

Output:

SELECT * FROM `products`

Find YouTube Video ID from YouTube URL

YouTube has so many types of URLs to embed the video on your site. Sometimes it’s difficult to find a single regular expression to parse all type of YouTube URL and retrieve the video ID from it.

YouTube has so many types of URLs to embed the video on your site. Sometimes it’s difficult to find a single regular expression to parse all type of YouTube URL and retrieve the video ID from it.

To retrieve the video ID from the YouTube URL, use this function,

function getVideoID($url) {
    $pattern = '#^(?:https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch\?v=|/watch\?.+&v=))([\w-]{11})(?:.+)?$#x';
    preg_match($pattern, $url, $matches);
    return (isset($matches[1])) ? $matches[1] : false;
}

Regular Expression explanation is as follows,

$pattern = '#^(?:https?://)?';    # Either http or https.
$pattern .= '(?:www\.)?';         #  Optional, www subdomain.
$pattern .= '(?:';                #  Group host alternatives:
$pattern .=   'youtu\.be/';       #    Either youtu.be,
$pattern .=   '|youtube\.com';    #    or youtube.com
$pattern .=   '(?:';              #    Group path alternatives:
$pattern .=     '/embed/';        #      Either /embed/,
$pattern .=     '|/v/';           #      or /v/,
$pattern .=     '|/watch\?v=';    #      or /watch?v=,    
$pattern .=     '|/watch\?.+&v='; #      or /watch?other_param&v=
$pattern .=   ')';                #    End path alternatives.
$pattern .= ')';                  #  End host alternatives.
$pattern .= '([\w-]{11})';        # Youtube video ids with standard length of 11 chars.
$pattern .= '(?:.+)?$#x';         # Optional other ending URL parameters.