PHP CheatSheet

Enable Error Display in PHP

ini_set('display_errors', 1);

PDO CheatSheet

This section includes cheatsheet of PDO.

PHP PDO execute() returning duplicate results

This can be solved by using FETCH_ASSOC with both fetch() or fetchAll() function.

Note that you might need to use \PDO depending upon namespacing in your project, especially if it gives fatal error.

// or
// use \PDO if you get an error

PDO::FETCH_ASSOC not working

If PDO or any method of PDO is not working then make sure that you’re calling the PDO via the namespace value properly, with a backslash, to make it return correctly, like this:

// solve PDO::FETCH_ASSOC gives fatal error

PHP ?? vs ?: (Null Coalescing vs Ternary Operator)

Null Coalescing operator: $a ?? $b;

Ternary Operator: $a ?: $b;

Difference example:

// ?? checks if value isset & is not null (via null | unset)
echo $var ?? 'not found';
// this will not throw an error

// ?: checks if value is not empty (!empty) too
echo $var ?: 'not found';
// this will throw an error: 
// NOTICE Undefined variable: var on line number 6

Check if session not started & then start

Below, we are defining two separate functions. This is intentional so that we can have more use cases for is_session_started().

function is_session_started()
    if ( php_sapi_name() !== 'cli' ) {
        if ( version_compare(phpversion(), '5.4.0', '>=') ) {
            return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
        } else {
            return session_id() === '' ? FALSE : TRUE;
    return FALSE;

function session_start_custom() {
    if ( is_session_started() === FALSE ) session_start();

PHP Fatal error: Uncaught Error: Call to a member function fetch_assoc() on boolean in error

This error usually happens when we’re trying to run fetch_assoc() on a non object. For this to work, we have to find out the issue happening at the mysql query level. This can be done by changing the mysqli->query to:

// from:
$mysqli_query = $mysqli->query($sql);
// to:
$mysqli_query = $mysqli->query($sql) or die($mysqli->error);

Leave a Reply

Your email address will not be published. Required fields are marked *

Hire Me!