Cheatsheet

Javascript
Sample async function
const fetchMeals = async () => {

	const response = await fetch('url-of-api'); // 1
	const responseData = await response.json(); // 2
	await new Promise(r => setTimeout(r, 2000)); // 3
	const processedMeals = await responseData.map((mealData) => { // 4
		return {
			id: mealData.id,
			name: mealData.name,
			description: mealData.description,
			price: mealData.price
		};
	});
	setMeals(processedMeals); // 5

}

fetchMeals(); // 6
  1. Get data
  2. Once data [response] is fetched, run this
  3. [temporary] Pause async function for 2 seconds
  4. Once data [responseData] is parsed to JSON, run this
  5. React code to set state i.e. do something with the resultant data
  6. Run the async function 'fetchMeals
Convert an array of values to a string list
  1. [create the array]const array = ['data1', 'data2', 'data3', 'data4', 'data5'];
  2. [join the array] array.join();
  3. [output]data1,data2,data3,data4,data5
  4. [join the array with commas & spaces] array.join(', ');
  5. [output]data1, data2, data3, data4, data5
map function samples

Sample JSON data

[{"id":1,"first_name":"Bambie","last_name":"Thorneywork","email":"bthorneywork0@phoca.cz"},
{"id":2,"first_name":"Nomi","last_name":"Outram","email":"noutram1@chron.com"},
{"id":3,"first_name":"Roanne","last_name":"Gravie","email":"rgravie2@census.gov"},
{"id":4,"first_name":"Anitra","last_name":"Kleinzweig","email":"akleinzweig3@hubpages.com"},
{"id":5,"first_name":"Jacklyn","last_name":"Burbank","email":"jburbank4@time.com"}]

Extra: sample data can be generated here: Mockaroo

Sample 1

Converts the raw data into an object with name-value pairs of our choice

const processedContacts = sampleJson.map((contact) => {
    return {
        id: contact.id,
        firstname: contact.first_name,
        laststname: contact.last_name,
        email: contact.email
    };
});

Sample 2

Converts the raw data into React components

const contactList = sampleJson.map((contact) => (
    const contactName = contact.first_name + ' ' + contact.last_name;
    <ContactCard
        key={contact.id}
        id={contact.id}
        name={contactName}
        email={contact.email}
    />
));
Regex's

Alphanumeric only

var b = a.replace(/[^a-z0-9]/gi, '');

(Replaces everything with '')

Object loops

Sample JSON data

[{"id":1,"first_name":"Bambie","last_name":"Thorneywork","email":"bthorneywork0@phoca.cz"},
{"id":2,"first_name":"Nomi","last_name":"Outram","email":"noutram1@chron.com"},
{"id":3,"first_name":"Roanne","last_name":"Gravie","email":"rgravie2@census.gov"},
{"id":4,"first_name":"Anitra","last_name":"Kleinzweig","email":"akleinzweig3@hubpages.com"},
{"id":5,"first_name":"Jacklyn","last_name":"Burbank","email":"jburbank4@time.com"}]

forEach

data.forEach(function (value){
    console.log(value)
});

data.forEach((value) => {
    console.log(value.id)
})

for-of

for (var value of data) {
  console.log(value.email);
}
Object deconstruction

Sample JSON data

{
    "product": {
        "id": 1,
        "name": "product name",
        "short_description": "short description",
        "description": "long description",
        "price": 20,
        "quantity": 5,
        "image1": "wolf.jpg",
        "image2": "pineMarten.jpg",
        "image3": "dog.jpg",
        "image4": null,
        "image5": null,
        "category": 1,
        "slug_text": "Hand_knitted_drawstring_bag_with_Devon_and_Cornwall_Longwool_yarn",
        "active": 1
    }
}
const {image1, image2, image3, image4, image5, name} = data.product;

Variables as specified are then available

Array filtering

Sample JSON data

images = [ "wolf.jpg", null, null, null, null ]
const filteredImages = images.filter(image => image !== null);

Returns:

[ "wolf.jpg" ]
String literals

String literals

var person = 'bob';
console.log (`[before] ${person} [after]`);

*Note use backticks `

Array loops

Array loops

forEach loop

var data = ["Sugar", "Flour", "Eggs", "Water", "Dates"];

let output = "<ul>"

data.forEach((ingredient) => {
    output += `<li>${ingredient}</li>`;
});

output += "</ul>"

console.log(output);

for-of loop

var data = ["Sugar", "Flour", "Eggs", "Water", "Dates"];

let output = "<ul>"

for (const ingredient of data) {
    output += `<li>${ingredient}</li>`;
}

output += "</ul>"

console.log(output);
React
Start a new (blank) React project
  1. npx create-react-app name-of-project
  2. npm start
  3. npm run build (for production build)
useState

Use 'useState' for small amounts of data that are exclusive to a component

Simple useState for showing/hiding content


import { useState } from 'react';

const ComponentName = () => {
    const [showSomething, setShowSomething] = useState(false);

    const showSomethingHandler = () => {
        setShowSomething(!showSomething);
    }

    return (
        <> <p>Always shown content</p>
        {showSomething &&
            <p>Content controlled by 'showSomething'</p>
        }
        <button onClick={showSomethingHandler}>Show/Hide</button> </>
    )
}

export default ComponentName;

Simple useState for incrementing/decrementing a counter

import { useState } from 'react';

const ComponentName = () => {
    const [counter, setCounter] = useState(0);

    const counterHandler = (direction) => {
        let newCounter = counter;
        if (direction === 'up') {
            newCounter++;
        } else {
            newCounter--;
        }
        setCounter(newCounter);
    }

    return (
        <button onClick={() => counterHandler('up')}>+</button>
        <button onClick={() => counterHandler('down')}>-</button>
        <p>{counter}</p>
    )
}

export default ComponentName;
PHP
Create and use hashed passwords

Create and use hashed passwords

Create:

$password = password_hash('user1234', PASSWORD_BCRYPT);

Result: $2y$10$XpTB2aSsvcG6a.kzskFZXOhzINxxf/iwMbSaSrZeW4u3optyeFRki

Check password:

password_verify('$_POST['password']', $logInID['password']);

password_verify('user123', '$2y$10$XpTB2aSsvcG6a.kzskFZXOhzINxxf/iwMbSaSrZeW4u3optyeFRki');

Result: boolean true|false 1|0

PDO insert

Insert data using a PDO statement

$db_servername = "localhost";
$db_username = "[DB USERNAME]";
$db_password = "[DB PASSWORD]";
$db_dbName = "[DB NAME]";

$pdo = new PDO("mysql:host=$db_servername;dbname=$db_dbName", $db_username, $db_password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $createOrder = "    INSERT INTO order_detail (name, email, telephone)
                        VALUES(:name, :email, :telephone)";
    $createOrder = $pdo -> prepare($createOrder);
    $createOrder -> bindParam(':name', $customer['name']);
    $createOrder -> bindParam(':email', $customer['email']);
    $createOrder -> bindParam(':telephone', $customer['telephone']);
    $createOrder -> execute();
    $orderId = $pdo -> lastInsertId();
$pdo = null;

This uses named variables.

'lastInsertId()' returns the ID of the inserted query.

Server
Configure Xampp for multiple sites
  1. Edit C:\xampp\apache\conf\httpd.conf
    1. Add listen xx around line 59, where xx is the port to listen on
  2. Edit C:\Windows\System32\drivers\etc\hosts
    ** Note : Run notepad or notepad++ in administrator mode
    1. Add reference to new site e.g. 127.0.0.1 newsitename.local
  3. Edit C:\xampp\apache\conf\extra\httpd-vhosts.conf
    1. Add reference to new site e.g.
      <VirtualHost *:81>
          DocumentRoot "C:/sites/newsitename/htdocs"
          ServerName newsitename.local
          <Directory "C:/sites/newsitename/htdocs">
              Require all granted
              Options Indexes FollowSymLinks
              AllowOverride All
              Order allow,deny
              Allow from all
          </Directory>
      </VirtualHost>
      
  4. Create directory for new site e.g: C:/sites/newsitename/htdocs
  5. Restart EVERYTHING
  6. Access site via http://newsitename.local:82/ where '82' is the new listen/VirtualHost you have just added
Taskrunners
Simple gulp file for scss

package.json

{
  "name": "siteName",
  "version": "1.0.0",
  "description": "admin for siteName",
  "main": "gulpfile.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/accountName/siteName.git"
  },
  "author": "author",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/accountName/siteName/issues"
  },
  "homepage": "https://github.com/accountName/siteName#readme",
  "dependencies": {
    "gulp": "^4.0.2",
    "gulp-cssnano": "^2.1.3",
    "gulp-sass": "^5.1.0",
    "gulp-sourcemaps": "^3.0.0",
    "sass": "^1.60.0"
  }
}

gulpfile.js

// -- Imports ----------------------------------------- //
    var gulp = require('gulp');
    var cssnano = require('gulp-cssnano');
    var sourcemaps = require('gulp-sourcemaps');
    const sass = require('gulp-sass')(require('sass'));
// ---------------------------------------------------- //

// -- Variables --------------------------------------- //
    var scssFiles   = 'includes/css/SASS/style.scss',
        scssWatch   = 'includes/css/SASS/**/*.scss',
        cssDest     = 'includes/css';
// ---------------------------------------------------- //

// -- Scss -------------------------------------------- //
    gulp.task('compileScss', function(){
        return gulp.src(scssFiles)
            .pipe(sourcemaps.init())
            .pipe(sass())
            .pipe(cssnano())
            .pipe(sourcemaps.write('.'))
            .pipe(gulp.dest(cssDest))
    });
// ---------------------------------------------------- //

// -- Watch ------------------------------------------- //
    gulp.task('default',function(){
        gulp.watch(scssWatch, gulp.series('compileScss'));
    })
// ---------------------------------------------------- //
  1. To set up npm install
  2. To run gulp
  3. Update any dependancies as required
Git
Git basics
  • Get the current status git status
  • Add all files git add .
  • Add a specific file git add .\includes\sections\git.php
  • Commit staged files git commit -m "commit message"
  • Commit staged files git commit -m "commit title" -m "commit message" (with multiple commit messages - first is title)
  • Push staged files git push
  • Pull latest from repo git pull
  • Clone a repo git clone https://url-of-repo
General issues
How to unblock a print queue

How to unblock a print queue

  1. Press Windows key + R, type services.msc and press Enter.
  2. Scroll down to the Print Spooler service and right-click on it and select Stop. In order to do this, you need to be logged in as Administrator.
  3. Next you need to go to the following directory: C:\WINDOWS\System32\spool\PRINTERS. Delete all the files in this folder. This will clear all print queues.
  4. Now you can go back to the Services console and right-click and select Start for the Print Spooler service.