[@messageCenter]

SQL Coding Standards

A Sample of My Coding Functions, for Quick Reference.Updated 1 year ago

Coding and Naming Standards:

On every project I've worked on, people have discussed coding & Naming Standards, but we always eventually realize that nobody has written these things down. So I have started these proposed standards:

  • Names: like_this
  • ID: Must be (INT) Named like: table_id

Coding Analogies

  • Variable- Cooking ingredient
  • Switch - Train switching station. or a choose your own adventure
  • If - For in the road
  • Break - Exit out of current Loop
  • Exit (or Die)- Quit IMMEDIATELY, and print something to the screen

Regex GEdit:

Delete every other line.
([^\n]*\n)[^\n]*\n
\1

Regex tester for Search AND Replace:

RegExe.com

Make all Links open in a New Window jquery.

<script>$("#content a[href^='http://']").attr("target","_blank");</script>
<script>$("#content a[href^='https://']").attr("target","_blank");</script>

SQL Queries

Count all Table Rows

SELECT TABLE_NAME, TABLE_ROWS FROM `information_schema`.`tables` WHERE `table_schema` = "adamwith_main";

Hwo to assign an array to two variables

I always forget :P
list($first, $second)=array(1,2);

Geo IP Location:

You are in: Columbus, United States

My Commonly Used Functions:

addorremovebitmapperm
array_map_assoc
arrayfromdb
arraytodb
backlink
bg
blackorwhitetext
buildsortstatement
buildwherestatement
bytestosize
cad
camelcasetowords
carousel
carouselyoutube
checkbox
checktable
cleanforanchorlink
cleanfordatabasefield
cleanforshorturl
cleanfortitle
cleanupmultifilearray
columntable
comparebydesc
convertcurrency
convertsmartquotes
createslideshowquickthumbnaildirectories
daysdifference
debugfilenotexist
decodebitmap
deletedirectory
dieonerrror
difficultytag
drawpagewithcontents
drawtable
emailabstract
emoji
fileexists
findpicfromanyextension
floatingblueimagebox
formatdollars
formatsize
getallguesses
getamazonpics
getbingimages
getcelebbox
getcelebpic
getcollageandimagemap
getcollageimg
getcurrencyrates
getcurrentquerystring
getdaysbetween
getfileextension
getfunctioncode
getidea
getimagefromandsaveto
getimagetype
getkey
getmetapic
getmovies
getparts
getquerysignature
getquestion
getrandompic
getscriptnamewithoutparams
getthumbnailoffilesin
getthumbnailpicsin
geturlpath
getvariablename
getweather
getweatherbox
googlestreetview
grammardate
hd
hextorgbcolour
hideemail
hitcounter
humantiming
imagecolorallocatebyname
imagettfstroketext
in_arrayresursive
incrementfilenameifexists
infopopup
isassoc
isdirectoryempty
ismobile
iso8859_1_to_utf8
isprivatecookieloggedin
isvalidpicextentions
isvalidurl
listbox
load404
loadsettings
locbox
lostfunction
makecollage
makeinsertstring
my_autoloader
phoneabstract
phptojavascriptarray
prettyarray
prettyarrayreturn
printbreadcrumb
privatebox
quickceleb
quickdbbutton
quickdbentryget
quickdbform
quickdbscript
quickdbtable
quickfetch
quickparse
quickparts
quickparts2
refreshbrokenpics
remotefiletype
removefileextension
returnshortenedstring
rgbtohexcolour
rootpage
runjswhenpicsloaded
show_ordinal
showdate
showitemsincategory
shuffleassoc
simpleslideshow
smartdate
strposa
subtractyearfrommovie
thumbnailexists
totaluplist
updatedatebox
url_exists
usd
usererrorhandler
videopopup
workinprogressbanner
yesno

View Function: getmetapic

function getMetaPic($title,$link,$debug=false,$categoryCode=false){
$toReturn='';
if($link==''){return '';}//Ignore if they didn't give a Title
$directory='images/meta/';
$imageURL=''.$directory.$title.'.jpg';
$possibleFiles=glob($directory.''.$title.'.*');
if($possibleFiles !=false) {
$metaFile=$possibleFiles[0];//file File
if($debug)$toReturn.='Debug Message: Found File: '.$title. ' ('.$metaFile.")
\n";
}
if($debug)$toReturn.='Debug Message: Possible Files:'.var_export($possibleFiles,true).'
';
if( isset($metaFile) && (file_exists($metaFile) ) ){
if($debug)$toReturn.='Debug Message: File Exists: "'.$title.'"
';
$imageURL='/'.$metaFile;
}else{
//die($title);
if($debug)$toReturn.='Debug Message: File Doesnt Exists: "'.$title.'", so we will look it up.
';
/*Uses /classes/class.OpenGraph.php
Add new meta tags to that
If it doesn't have meta tags, add a Fallback
*/
if( strpos($link,'/')==0 ){
$imageURL='/themes/public/images/favoriteBox'.$link.'.jpg';
//die('LOCAL PAGE');
}else{
echo 'Error #345345345345: '.$title.' ==='.$link.'';
//$metaTags = OpenGraph::fetch($title,$link);
$metaTags = quickFetch($title,$link);
//prettyArray($metaTags);die('metATags GO HERE: '.$link.'
');
if( strpos($link,'ebay')!=false ){
$metaTags->image=str_replace('1000x1000','225x225',$metaTags->image);
//prettyArray($metaTags);die('ebay'.$link);
}

if( getFileExtension($link)=='jpg' ){
$imageURL=$link;
//die('Already a Image URL');
}else if( strpos($link,'amazon')!=false ){
$searchFor=array('product/','dp/');
$ASIN=false;
foreach($searchFor as $eachSearch){
if( $startAt=strpos($link,$eachSearch) ){
if($startAt!=false){
$ASIN=substr($link,$startAt+strlen($eachSearch),10);//die($ASIN);
break;
}
}
}
if($debug)$toReturn.='Amazon ASIN Found: "'.$ASIN.'"
';
if( ! $ASIN){return 'Error: Unable to Find Product Code';}
$imageURL='https://ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&MarketPlace=US&ASIN='.$ASIN.'&ServiceVersion=20070822&ID=AsinImage&WS=1&Format=_SL250_&tag=adamwithers06-20';
//die($imageURL);
/*$query = array(
'Operation'   =>'ItemLookup',
'ResponseGroup' =>'Medium,Images',
'IdType'    =>'ASIN',
'ItemId'    =>$ASIN
);

$allPictureURLs = getAmazonPics($query,'MEDIUMIMAGE');//relies on /includes/globalVars.php variables
//prettyArray($allPictureURLs);prettyArray($query);die('getAmazonPics
');
$imageURL=$allPictureURLs[1];
*/
}else{
//var_dump($metaTags);die('not amazon, not ebay'.$imageURL.'
');
if(isset($metaTags->image) && $metaTags->image!=''){
$imageURL=$metaTags->image;
}else{
echo('Error #34sd512: Unable to set $imageURL
'.$toReturn);
}
}
if($imageURL=='{{::og.image}}'){
die('Error #2321424: $imageURL is corrupted for: '.$title.'.
'.$toReturn);
}
if(isset($imageURL) && $imageURL){
if($debug){$toReturn.='Debug Message: Writing File: '.$title.'=>'.$imageURL.'
';}
if(substr($imageURL,0,2)=='//'){
$imageURL='https://'.substr($imageURL, 2);
}
if( ! url_exists($imageURL) ){
//$imageURL='/'.$imageURL;
//echo('Adding a slash to imageURL:'.$imageURL.'
');
}

if(file_exists($imageURL) ){
$imageData=@fopen($imageURL, 'r');
//echo 'imageData: '.var_export($imageData,true).'
';
}else{
//Might want to die?
echo('Error #241234: File does not exist: '.$imageURL.'
Cant save: '.$link.'
');
}
//echo('$imageURL: '.$imageURL.'
$imageData: ' );
if(isset($imageData) && $imageData!=false){
$ext=strtolower(getFileExtension($imageURL));
if($ext==''){ $ext='jpg';}
file_put_contents($directory."".$title.'.'.$ext, $imageData);
//die('aaaa' );
}else{
//die('bbbb' );
//If you STILL haven't found a link, we will try to CURL it
$ch = curl_init($imageURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 7);
$imageData = curl_exec($ch);
$curl_info = curl_getinfo($ch);
curl_close($ch);
//die($imageData);
//die('http_code='.$curl_info['http_code']);
if($curl_info['http_code']==200) {
file_put_contents($directory."".$title.'.'.strtolower(getFileExtension($imageURL)), $imageData);

}else{
$toReturn.='Error: Unable to Get Picture Data for "'.$title.'" from "'.$imageURL.'".
'.var_export($imageData,true).'
';
}
}
}
}
//prettyArray($metaTags);die('Everything from: '.$link);


}

$toReturn='
'.
($link!=''?'':'').''.$title.''.
'
'.
($link!=''?''.
'
'
:'').
( isPrivateCookieLoggedIn()===true?''.
'
'
:'').
'
'."\n";
return $toReturn;
}
***Declared In:/home4/adamwith/public_html/includes/functions/adamwithers.ca.php

Add a hyphen to lists when Copying & Pasting

const prependChar = "-";
document.addEventListener("copy", function(e) {
const selected = getSelectionHtml();
if (selected.html.includes("
  • ")) { const ul = selected.container.querySelectorAll("li"); Array.from(ul).forEach(c => { if (c.tagName === "LI") { c.innerText = prependChar + " $$$ " + c.innerText; } }); // Remove unwanted whitespace const html = selected.container.innerHTML.replace(/(^|>)[ \n\t]+/g, ">\n"); const list = `
      ${html}
    `; const wrap = document.createElement("div"); wrap.innerHTML = list; e.clipboardData.setData("text/plain", wrap.textContent); e.clipboardData.setData("text/html", list); e.preventDefault(); } }); function getSelectionHtml() { let html = ""; let container; if (typeof window.getSelection !== "undefined") { const sel = window.getSelection(); if (sel.rangeCount) { container = document.createElement("div"); for (let i = 0, len = sel.rangeCount; i < len; ++i) { container.appendChild(sel.getRangeAt(i).cloneContents()); } html = container.innerHTML; } } else if (typeof document.selection !== "undefined") { if (document.selection.type === "Text") { html = document.selection.createRange().htmlText; } } return { html, container }; }