Coding Examples
Pull News Details From Database
Project Name: PHP Recreation of Netmatters Homepage
Coding Languages Used: PHP
The Code:
<?php
// call the database
require_once 'db.php';
//select the needed columns from the database for the news section and save it as a string variable
$sql = "SELECT Article_Class, Tag,
Image, Alt,Title, Description,
Button_Color, Author_Image,
Author_Alt, Author_Name, Date FROM `news` ORDER BY Date DESC LIMIT 3";
//prepare database and run query
$stmt = $pdo->prepare($sql);
$stmt->execute();
//save all rows to a Associate Array
$allNews = $stmt->fetchAll(PDO::FETCH_ASSOC); ?> What The Code Does: It takes the values from table news and then places them in an associative array which will then be used to echo the view accordingly to produce multiple news article cards.
Reasons For Using This Code: I chose to use this style coding as with pdo it allows more multipurpose of various different databases without the need to rewrite code and using prepare and execute with the prepared statement will prevent SQL-injection, fetch all and making it an associative array allows for high volume of rows to be pulled from the database and to store the variables efficiently in order to prevent duplicates and errors.
Note: The limit of 3 in the query is because I wanted to only display the 3 newest news articles if newer ones were entered into the database.
Full Code GitHub Link: https://github.com/RJKLavender/Netmatters-Old-Home-Page-Assessment/tree/PHP-Website-
Client Slide Validation Checks
Project Name: This code is used on all projects containing a Form.
(JS Array, Netmatters Contact Page and This Portfolio)
Coding Languages Used: Javascript
The Code:
// Client Side Validation Rules
const validationOptions = [
//checks if someone has entered text into field
// and that it doesn't exceed maximum set length
// and is above the minimum set length
{ attribute: 'data-v-required',
isValid: input => input.value.trim() !== '',
errorMessage: (input, label) => `${label.textContent} is required`
},
{ attribute: 'data-v-required',
isValid: input => input.value.trim() !== null,
errorMessage: (input, label) => `${label.textContent} is required`
},
{ attribute: 'data-v-required',
isValid: input => input.value.trim() !== undefined,
errorMessage: (input, label) => `${label.textContent} is required`
},
{
//checks email and phone number against pattern provided for valid email and phone number
attribute: 'data-v-pattern',
isValid: input => {
// Get the raw string from the attribute
const patternString = input.getAttribute('data-v-pattern');
// Create the RegEx with the case-insensitive 'i' flag
const patternRegEx = new RegExp(patternString, 'i');
// Test the TRIMMED value
return patternRegEx.test(input.value.trim());
},
errorMessage: (input, label) => `Is Not a Valid ${label.textContent}`
},
{
attribute: 'customminlength',
isValid: input => input.value.length >= parseInt(input.getAttribute('customminlength')),
errorMessage: (input, label) => `${label.textContent} Has Too Few Characters`
}
]
//unpacks array into variables and checks for errors in said field
const validateformField = formField => {
const label = formField.querySelector('label');
const input = formField.querySelector('input, textarea');
//sets the error value to false by default
let formFieldError = false;
//checks agaisnt the vaildation options for errors
//uses the attribute and the value of the input to determine if errors or not
for (const option of validationOptions) {
if(input.hasAttribute(option.attribute) && !option.isValid(input)) {
//changes the border to red
input.classList.add('field-error');
//since error was found sets the error value to true
formFieldError = true;
setTimeout(() => {
input.classList.remove('field-error');
}, 30000);
}
}
//if no errors are found the error value stays false so the next if statement can check it.
// checks for no errors and styles the form accordingly uses formfielderror value to check this
if (!formFieldError) {
//changes the border back to normal
input.classList.remove('field-error');
}
return formFieldError;
}; What The Code Does: This is the code I have used and adapted for client side validation by checking if the html field has the set attributes and looking for the values set by those attributes then comparing them against the rules given in validationOptions.
The validateformfield function is what is sued to check the html of the form against the rules and then produce the error messages as needed. formfield error is hard coded as false which is then checked again later to see if the fields are valid so it becomes true if there is an error.
There is also a timer inside this code for how long the error message should be displayed for.
Reasons For Using This Code: I had several problems getting the pattern check to work properly so I overcame this issue by defining the patternString the same as the variable in the html form and then using the regEXP function to check it with an insensitive i flag.
This makes sure any accidental of capital letters are changed to match the regex as well fixing path for the email as well. The rest of the rule to define it in the script also helped me get around the issue of test@test.com test being successful as it would trim after any space and read it as one entry which would create an invalid email entry.
I used this method as then the html values can be adapted for any site based on needs and no javascript would need to be changed other than the defined classes allowing it to be reusable client side validation code.
Full Code GitHub Link: N/A
Add to Image Gallery Function
Project Name: JavaScript Array Image Generator
Coding Languages Used: JavaScript
The Code:
// Add Image to Collection Function
addToCollection.addEventListener('click', () => {
let imgarray = {};
// checks if images for this user are already in local storage
if (localStorage.getItem(currentEmail)) {
imgarray = JSON.parse(localStorage.getItem(currentEmail));
}
let imgElement = document.querySelector('.img-container img');
// gets values of the image
let imgData = {
id: imgElement.id,
src: imgElement.src,
alt: imgElement.alt
}
//if image is already in local storage for this user display error message
if (imgData.id in imgarray) {
successGenerateMessage.style.color = '#d64541';
successGenerateMessage.textContent = `Current image is already in ${currentEmail} image collection.`;
successGenerateMessage.classList.remove('invisible');
temporaryErrorMessage(successGenerateMessage);
} else {
// if it is a new image then add it to local storage and display successful message
let img = document.querySelector('.img-container img');
// Add image to local storage and array
imgarray[imgData.id] = imgData;
localStorage.setItem(currentEmail, JSON.stringify(imgarray));
successGenerateMessage.textContent = `Current image has been successfully added to ${currentEmail} images collection.`;
successGenerateMessage.style.color = '#10d53b';
successGenerateMessage.classList.remove('invisible');
temporaryErrorMessage(successGenerateMessage);
// updates the display container for new image
let displayContainer = document.querySelector('.display-imgs-box');
//check if other images are in display container
let hasImgChild = displayContainer.querySelector(':scope > img') !== null;
if (hasImgChild) {
let newImg = document.createElement('img');
newImg.id = imgData.id;
newImg.src = imgData.src;
newImg.alt = imgData.alt;
displayContainer.appendChild(newImg);
//reruns the dialogue function so can be used for the new images
DisplayLargeImg();
} else {
// If this is their first image add span children to display container
let hasSpan = displayContainer.querySelector(':scope > span') !== null;
if (hasSpan) {
let span = document.querySelector('.display-imgs-box span');
displayContainer.removeChild(span);
let newImg = document.createElement('img');
newImg.id = imgData.id;
newImg.src = imgData.src;
newImg.alt = imgData.alt;
displayContainer.appendChild(newImg);
//reruns the dialogue function so can be used for the new images
DisplayLargeImg();
}
}
}
}); What The Code Does: This function adds the chosen random image to that user's array collection. It will check if the user already contains the image and then update their local storage accordingly before then updating the display container containing a gallery of all their chosen images.
This function runs when the user clicks the add to collection button above the image that is generated.
Reasons For Using This Code: I chose to extract the image from the container rather than from the fetch command as it prevents any issues with the server and doesn't require more comminations to be made. It is stored in local storage rather than cookies to lower loading times between images being added and removed from the container in the browser.
This function will not allow you to add the same image that is already in the collection as I wanted the app to be a useful gallery of images that the user has chosen.
Once the image is added to the array and local storage with the chosen image its details will then be transferred to the visual gallery at the bottom of the app. This is done by creating new children in the container. So the gallery doesn't have a limit but if limitations need to be added they can be in the future.
Full Code GitHub Link: https://github.com/RJKLavender/Javascript-Array-For-Imgs