PHP CheatSheet


Enable Error Display in PHP

error_reporting(E_ALL);
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.

fetch(PDO::FETCH_ASSOC)
// or
fetchAll(PDO::FETCH_ASSOC)
// 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
\PDO::FETCH_ASSOC

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

Leave a Reply

Your email address will not be published.