Friday, September 21, 2018

Determining the Element Clicked on in jQuery

In jQuery, you can easily find out when an element itself is clicked on, but binding with the click event, like so...

$('#MyElement').click(function(event) {
console.log("I just clicked the element with the id of Myelement!");
});

But in more complicated scenarios, several elements will trigger a shared function, and you need to know which element was clicked from that shared function.

That would be like this...

$('#MyElement').click(function(event) { return doSomething(event);}
$('#MyOtherElement').click(function(event) { return doSomething(event);}

In this case, you could find out which element was clicked by using the event object...

function doSomething(event) {
console.log("Just clicked the element with an id of..." + event.target.id);
}

The event.target object will tell you almost everything you need to know about what was clicked.

Thursday, September 20, 2018

Capturing a Key-Press/Key-Down Event for the Enter Key in jQuery

You may want to capture an enter key action whenever the user hits the enter key. This can be used to submit a form without having to use the mouse, or it can provide some other feature.

To do this, we bind the keydown() event to the document, and check the event to make sure it is 13 (the enter key). A different integer represents a different key (27 is the escape key, etc.).

We do the binding like this...

$(document).keydown(function(event) {
if (event.which === 13) {
// do something now that the enter key is hit
}
});

You can also use the keypress() event. But there is a problem with keypress -- this event does not fire for the escape key, or the up-down arrows. It only fires for keys whose purpose is to create a character.

Wednesday, September 19, 2018

Using jQuery to Change or Set Background-Color

You can change the background-color of any element easily in jQuery. All you need is any of these...

$(this).css('background-color', 'red'); // red
$(this).css('background-color', '#000'); // black
$(this).css('background-color', '#00FF00'); // green

If you are not dealing with a jQuery event-handler (where "this" is available), you can use a selector to get and adjust any element's background-color, like so...

$("#MyElementId").css('background-color', 'red'); // red
$("#MyElementId").css('background-color', '#000'); // black
$("#MyElementId").css('background-color', '#00FF00'); // green

Not only can you change any background color now, but you can use the same process to adjust any part of an element's style.

Tuesday, September 18, 2018

How do I create an Iframe and insert it into my webpage with only JavaScript?

There are times when you will want to create and insert an Iframe page onto the current page the user is on.

This gives you a number of advantages, like allowing you to load a whole new webpage or website in the iframe (though some sites disallow others to use them through iframes, such as Google).

In JavaScript, the code to create the iframe is this simple..

var iframe = document.createElement('iframe');
iframe.src= "http://www.earthfluent.com";

You'll notice that, it won't be a very useful iframe unless you define some basics, like width and height...

iframe.width = "200";
iframe.height = "200";

Then you append it to your document with JavaScript...

document.getElementById("PlaceIframeHere").appendChild(frame);

Or with jQuery...

$("#PlaceIframeHere").append(frame);

Monday, September 17, 2018

Removing Windows ^M Characters From Linux Vim Editor

If you open a document in vim, and you see it littered with ^M characters, that means that someone saved this document in MicroSoft Windows.

But the problem (^M characters, not MicroSoft) is easily fixed!

Simply typing this with the CARROT and M keys will not be enough...

:%s/^M//g

The ^M can be produced by hitting the control key and V, and then, hitting the control key and M.

Once that command is executed with the correct control-key sequence, you will have document freshly cleaned of ^M characters.

Sunday, September 16, 2018

Why is Varchar(255) in MySQL when 2^8 is 256?

If you look in many database implementations, you will see that VARCHAR limits are not at 256 (2^8), but they are at 255.

This 255/256 value is the number of characters storeable in the field. If the index starts at the 1st character, you would think that it should end at the 256th character, because 2^8 = 256.

According to the MySQL documentation, the size of a varchar field is actually "1 + (0 to 255 bytes)", or "2 + (256 to X bytes", if over 255.

Source: https://dev.mysql.com/doc/refman/8.0/en/storage-requirements.html

That delimiting mark, between 255 and 256 bytes, is defined not by logical limitations of data storage, but by the MySQL implementation itself. By using the 255 limit, you are using one less byte than if you had 256.

This is so that MySQL can count the length of a field (from 0 to 255, not from 1 to 256) in a single byte.

Be aware, though: If any of the characters are UTF-8, that means they will be multi-byte encoded, and this will definitely go over the 255 byte limit in MySQL and use the extra byte, even if it doesn't warn you of that.

Saturday, September 15, 2018

What are MySQL's Text Max-Length Limitations?

If we look at the MySQL docs, we can see that there are certain limitations to the length of Text-type fields in the MySQL DB...

TINYBLOB, TINYTEXT: Can Store 255 Bytes (2^8 - 1 bytes)
BLOB, TEXT: Can Store 64 KB (2^16 - 2 bytes)
MEDIUMBLOB, MEDIUMTEXT: 16 MB (2^24 - 3 bytes)
LONGBLOB, LONGTEXT: 4GB (2^32 - 4 bytes)

Source: https://dev.mysql.com/doc/refman/8.0/en/storage-requirements.html

You may also want to consider CHAR() and VARCHAR() types when taking into consideration fields that can store text and their limitations.

Friday, September 14, 2018

Speed Up and Secure SSH to Linux by Disabling GSSAPI-Authentication

Every time you try to connect with SSH after you enter your username, GSSAPI Authentication will attempt to authenticate you using the Kerberos protocol.

The problem with this is that nobody sets up GSSAPI Authentication services: this is both a waste of time and a security risk, as you are attempting to authenticate a service that you're not hosting, and is therefore prone to "Man in the Middle" attacks.

Unfortunately, GSSAPI Authentication with SSH in Linux is the default option. You can easily turn it off by doing the following. Open the SSH config file...

[user@localhost /]$ vi etc/ssh/ssh_config

And then find this line...

Host *
GSSAPIAuthentication yes

You may not have GSSAPIAuthentication set there yet, but you will want to find the line beginning with Host *. And then you can adjust it like so...

Host *
GSSAPIAuthentication no

Now your SSH will load instantly and securely.

Thursday, September 13, 2018

Detect a CheckBox's Checked Status in JavaScript or jQuery

Checkboxes are an important part of forms, and knowing whether they are checked, in JavaScirpt and jQuery, can be very useful.

Standard checking in JavaScript is very simple...

console.log("Checked status?" + document.getElementById('MyCheckBox').checked);

Checking in jQuery is similarly not very difficult...

console.log("Checked status?" + $('#MyCheckBox').is(":checked"));

If you have a newer version of jQuery (v. 1.6+), the following will also work...

console.log("Checked status?" + $('#MyCheckBox').prop('checked'));

Make sure not to mix these up, or you will get bad results. jQuery selectors return an array of matched elements. If you try to look at $('#MyCheckBox').checked, you will always see false, whereas $('#MyCheckBox')[0].checked would be more likely to work.

Wednesday, September 12, 2018

Removing Symbols from a UTF-8 String and Retaining the Characters in PHP

You will often have strings that contain symbols, where you only want to extract just the text component of this string.

Using a regular expression (regex) in PHP, you can do this quite easily...

$string = "12345-hello, 汉语!!!";
$string = preg_replace('/[^(\p{L}\p{N}\s)]/u', '', $string);
print($string); // output is: 12345hello 汉语

Each part of the preg_replace here can be explained without much effort.

/regex/u - The two slashes indicate what is matched against. The U indicates UTF-8.

[class] - Within this, the two brackets indicate the one single class of values considered valid.

^(values) - We are looking for things that do not match values.

\p{L} - This value is all UTF-8 characters.

\p{N} - This value is all numbers.

\s - This value is all white spacing.

So, anything that doesn't match a letter, a number, or a space (i.e., /[^(\p{L}\p{N}\s)]/), is replaced with '', or the empty string.

Tuesday, September 11, 2018

Converting Accented Characters to Non-Accented Equivalents in PHP

For some reason or other, you may want to have a string of accented characters converted to its equivalent, such as "hëllo" to "hello".

Doing this in PHP is easy. You will have some input like this...

$input = "hëllo";

Then you can convert and see the output like this...

$output = iconv('UTF-8', 'ASCII//TRANSLIT', $input);
print($output);

Output here is "hello", and our problem is solved very easily!

Of course, for the most part, you should not need to do this. Accepting the entirety of UTF-8's range in diversity and color is usually a good thing for any code solution.

Monday, September 10, 2018

How do I convert to/from 24-hour time and AM/PM time in PHP?

In databases, times and datetimes may be stored as "13:30:00" or "1984-05-01 15:45:59".

But you may want to convert this to something that displays with AM/PM, or maybe you want to collect a time that is AM/PM and store it according to your DB schema.

You can display 24-hour time in AM/PM with...

print date('G:ia', strtotime("13:30:00"));

And a 24-hour datetime with in AM/PM with...

print date('Y-m-d G:ia', strtotime("1984-05-11 13:30:00"));

If you wanted to go in the opposite direction, and display an AM/PM time with 24-hour time...

print date('H:i:s', strtotime("1:30 AM"));

And if you want to display AM/PM datetime in 24-hour datetime format...

print date('Y-m-d H:i:s', strtotime("1:30 AM"));

Sunday, September 9, 2018

How do I evaluate a Mathematical Expression or Formula in Java?

You may have an expression like "1900 + 84" that you want to be evaluated, to something like "1984." You can do that easily in Java.

Make sure to import the correct packages...

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

In main(), you will need to instantiante the evaluators with...

ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");

And then you can use this engine by means of this...

System.out.println(engine.eval("1900+84"));

Note that this is a script-evaluator, so "100;1900+84" will result is just 1984. Additionally, you will want to cleanse any input that may be placed into engine.eval(), especially if you are working on a web-server.

Saturday, September 8, 2018

What are the Best Practices for Database DateTime Storage?

Dates are datetimes are common values that coders are going to want to save. But what is the ideal format?

With MySQL, you have the options of Date (default "0000-00-00"), DateTime (default "0000-00-00 00:00:00"), and even Year ("default "0000").

Any of these should fit your purposes for storing recent data. The only limits are that Date and DateTime cannot store years older than 1000, and Year has even smaller range of valid values.

There are advantages to storing dates this way: timezones are built-in to MySQL which can be applied or unapplied easily, the data is fit into as few bits as possible to get you the best storage, you can always sort by using the "greater than" or "lesser than" operators, etc..

Some people store this value as a string. But that is quite a bit more data to hold into the system, and it will accept invalid date/datetime values. This should be avoided.

Some people store this value as an integer, using the epoch time schema. But epoch time is timezone-less, and there will be no way for MySQL to be able to adjust or unadjust this time for timezones. This should be avoided.

Use MySQL's Date or DateTime.

Friday, September 7, 2018

How do I change an Element's Class in JavaScript?

You can manipulate an element in jQuery by selecting it by its class, like so...

$(".SomeElementClass").SomeAction(...)

The period here indicates that "SomeElementClass" will match on elements like this...

<element class="SomeElementClass">

If you want to change the class, things can become a bit more tricky, but it is very possible...

const element = $('.SomeElementClass');
element.classList.remove('SomeElementClass');
element.classList.add('BrandNewClass');

Now, when looking at the DOM, your element will now be...

<element class="BrandNewClass">

The same approach can be used to change an element's id attribute, as well.

Thursday, September 6, 2018

Why Custom-Delimited Data Sets are Bad and Should Be Avoided

With MySQL and other database options, you can store data to fields for tables. And sometimes, people are tempted to store a list to a field, like this: "1,2,3,4,5".

When the coder of this needs to go over the list, they retrieve it from the database, break it up by the commas using explode() or split(), depending on the language, and then iterate over the list.

There are a number of reasons why this is a problematic approach to whatever you're trying to solve.

The problem is that you need the whole list every time you want to do something with it.

Want to count how many 1's or 2's or 3's in the list? You must loop over the entire list.

Want to get only numbers when they are 4 or 5? You must loop over the entire list.

Want to delete just one value? Want to delete values greater than 5? Loop the list, loop the list, loop the list, and that's a lot of looping.

Besides performance issues, there are technical limitations.

How do you guarantee that something like "skyscraper" doesn't show up in your list of numbers? How do you escape characters like your delimiter (a comma in this case), which may appear in words, like this list: "barn", "skyscraper", "appartments, condos, etc."?

These performance and technical issues mean that few programmers actually implemented delimited lists. So, if you're going to use it in your project, it's going to be something that new people need to stress over and re-learn, when there are many more commonly accepted practices that solve this problem.

Wednesday, September 5, 2018

Importing or Including Other JavaScript Files from Your JavaScript Code

You may have multiple JavaScript files, and you want them all to be included within one page. Normally, that would be several script tags at the head of the document, like so...

<html>
<head>
<script src="MyScript.js"></script>
</head>
<body>
</body>
</html>

But, you may need to determine the name of the JavaScript file you need using JavaScript ocde itself. For instance, you may not be certain that you need MyScript.js, unless the user is logging in through a certain service.

With jQuery, you can include the file very cleanly and with high browser-compatibility. From your JavaScript source library, run this command...

$.getScript("MyScript.js", function() {
console.log("Script loaded!);
});

If you just want to use JavaScript, and nothing else, then you can get away with adding an element of the script type...

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "MyScript.js";
document.appendChild(script);

Then MyScript.js will have been loaded and is then available for use in the local, calling script.

There are a number of other options for handling this: ES6 options, AJAX query options, Node.JS packages, etc., but these are the simplest approaches.

Tuesday, September 4, 2018

What is a stacktrace? How do I use a stacktrace to debug my code?

A stacktrace is a list of all the functions and all the files called at a particular point in a piece of code. It may be generated by a programming exception (a runtime error), a break-point, or simply by developer-triggered logging.

If your code crashes, this is useful because it will tell you everywhere that code executed in order to produce the error. Generally, these are good places to start looking for finding a solution to the bug.

Take a look at this PHP error stacktrace...

Stack trace:
#0 /home/anarchocommie/classes/Format/HTML.php(181): users->viewuser()
#1 /home/anarchocommie/classes/Networking/Handler.php(536): HTML->Display()
#2 /home/anarchocommie/classes/Networking/Handler.php(520): Handler->HandleRequest_Content_Format()
#3 /home/anarchocommie/classes/Networking/Handler.php(458): Handler->HandleRequest_Content()
#4 /home/anarchocommie/revoltlib.com/index.php(9): Handler->HandleRequest()
#5 {main}

In this particular stacktrace, index.php was first called (at line 9 in index.php), which then called Handler->HandleRequest(), then Handler->HandleRequest() called Handler->HandleRequest_Content(), and then Handler->HandleRequest_Content() called Handler->HandleRequest_Content_Format(), and then Handler->HandleRequest_Content_Format() called HTML->Display() -- and so on.

Using a stack trace like this, you can find out how and why your errors occurred.

Monday, September 3, 2018

Why is document.write() a bad coding decision in JavaScript?

If you want to send content to a browser, there are many options. But one of them that you should avoid is document.write(), which may appear as...

document.write("<html><body>Hello!</body></html>");

This is considered poor form for a number of reasons.

First, it completely overwrites all content on the page with whatever is given to the write() function. So, if you have any other HTML on the page, it will disappear.

That means that all future coding and development needs to be done with this document.write("") function, and that's just an unnecessary complication.

The real problem is that it's difficult to work with. A coder using document.write()'s all over their script will take much longer to finish than one who is using proper DOM manipulations (like using element.innerHTML(), jQuery's append(), etc.).

There are also technical problems: XHTML does work with document.write("").

There are also security problems: Google Chrome will refuse to run document.write("") if it contains anything in the write("") which was from a POST or GET query, or if it suspects that any cross-site scripting injection is taking place.

There are also performance problems: Google Chrome itself will give the warning that document.write("") may slow down your webpage by "tens of seconds," according to the Google Developers blog (https://developers.google.com/web/updates/2016/08/removing-document-write).

Sunday, September 2, 2018

What is the maximum length of a URL in a browser?

Since the web runs on links, it is worth while to know the max length of a link : there is no limit at all in the specification. But, browsers will have limits.

The exact specification reads :

Servers MUST be able to handle the URI of any resource they serve, and SHOULD be able to handle URIs of unbounded length if they provide GET-based forms that could generate such URIs.

(Source: http://www.faqs.org/rfcs/rfc2616.html)

However, Microsoft Internet Explorer only can handle around 2,000 characters. (Source: https://support.microsoft.com/en-us/help/208427/maximum-url-length-is-2-083-characters-in-internet-explorer)

More than that, a webpage whose url is 2,000 characters will take longer to load than one whose length is 20 characters. At the very least, because your computer needs to download 1,980 characters less.

In terms of networking, domain lookup times, or file lookup times, longer names similarly slow things down. Additionally, search engines dislike overly long URLs, so, if SEO is important, try to keep to a limit of 100 or fewer characters.

Saturday, September 1, 2018

Difference between Single-Quoted and Double-Quoted Strings in PHP

There are two types of quoted strings in PHP: single-quoted and double-quoted.

With a single quoted string, characters using by PHP to define a string must be escaped, like so...

$stringa = 'hello, \'friend\', how are you?'; // string: hello, 'friend', how are you?
$stringb = "\\file\\directory\\location.php"; // string: \file\directory\location.php

But you may also have a double-quoted string, which means that the content is more dynamic, like so...

$stringc = "hello, $friend"; // string: hello joe, ann, tom, etc..
$stringd = "where are all the ${type}s?" // string: where are all the friends? books? beers?

Single-quoted strings always execute much faster than double-quoted strings. But there are things in double-quoted strings that cannot be done by single-quoted strings alone. They will need concatenation, like so...

$stringe = "hello, " . $friend; // string: hello joe, ann, tom, etc..
$stringf = "where are all the " . $type . "s?"; // string: where are all the friends? books? beers?

If you are using single-quoted strings, you only get this performance boost by using apostrophes ("static strings", AKA: Single Quoted Strings), and not by using the quotes ("interpolated strings", AKA: Double-Quoted Strings).

Friday, August 31, 2018

Changing the Filename of a File Downloaded over a PHP Script

You may be downloading files on your server with PHP by a combination of the header() and readfile() functions, like so...

header("Content-disposition: attachment;filename=MyFileName.txt");
readfile("../data/MyFileName.txt");

The filename on the server, and the one the user sees, will both have the same name. But you can change the filename the user sees, with something like this...

header("Content-disposition: attachment;filename=MyUSERONLYFileName.txt");
readfile("../data/MyFileName.txt");

Your server knows to look for the file in ../data/MyFileName.txt, and now, your user will receive a file with teh name of MyUSERONLYFilename.txt, instead of MyFileName.txt.

Thursday, August 30, 2018

How do I Download a File to the User with my PHP script?

If you have a text file on your PHP server, you may have tried to download it through your PHP script with just this...

readfile("../data/MyTextFileName.txt");

But, as you would have noticed, it doesn't download the file. It displays the file contents in the browser.

To download the file, you must also include headers, used by HTTP to determine how to treat the web server's response, like this...

header("Content-disposition: attachment;filename=MyFileName.txt");
readfile("../data/MyTextFileName.txt");

After running the above, the user will be prompted with a question about whether they want to open or save a downloaded file, or however their particular browser is configured to handle downloads.

Wednesday, August 29, 2018

Creating a GZip Archive on Your PHP Server to Serve to Web Users

Gzip is a popular zip-archive format for storing files in the long-term. Users benefit from this by reducing the download time, or by being able to group files together in a single download link.

You may have files on your PHP server, of any type (image, documents, code, etc.), and you may want to zip these files in a GZip archive automatically with your PHP script.

You can create a gzip file with something like this...

$filep = gzopen("../data/MyZipFileName.gz", 'w9');

Then you write whatever text you want to it with something like this...

gzwrite($filep, $text);

When you are finished, you let the PHP server know you're done by adding this to the end of your script...

gzclose($filep);

If you want to download this as a file, you need to send file headers, so that you download the gzip file at the PHP URL, instead of just looking at the gzip file contents through the browser (which would be a garbled mess, as it is a compressed archive).

You can do that with this...

header("Content-disposition: attachment;filename=MyArchiveFile.gz");
readfile("../data/MyZipFileName.gz");

Tuesday, August 28, 2018

Downloading and Unzipping GZip on Your PHP Server From Another Web Server

Some site may offer a gzip file that you want to run with your PHP script, but that gzip file is always being updated and you want your script to download the newest version and use its contents.

This can be done very easily.

First, download the file you want to unzip, using something like this...

$file = file_put_contents("../data/SomeZipFileLocation.gz", fopen("SomeURL", 'r'), LOCK_EX);

Then you can read the contents like this...

$file = gzopen("../data/SomeZipFileLocation.gz", 'rb');
while (!gzeof($file)) {
print(gzread($file, 4000));
}

This will loop through each of the 4,000 bytes in the file from the gzip and display them.

Using this technique, you won't ever have to manually download and unzip these gzipped files to use the newest version with your code.

Monday, August 27, 2018

Using HTAccess to Redirect All Users (and POST data) to the Same URL

With the Apache .htaccess file, you can control a good number of things on your server.

If you turn on the RewriteEngine, you can have one URL example.com/123, always return the results of another URL, like example.com/index.php?id=123.

To do this, you need to have a .htaccess file in the base directory of your apache htdocs folder. It should start with this...

RewriteEngine On
RewriteBase /

And, it can redirect everyone to index.php with this...

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,NC,L]

You can change index.php to anything you like, of course. Then you can get the information about the original URL by using the $_POST parameters, which you can see with...

print_r($_POST);

Sunday, August 26, 2018

How do I Salt and Encrypt Passwords in PHP?

Salting a password occurs when you add text to a password to make it longer and more complex.

For instance, "myPassWord" would be "myPassWordSomeSalt". Since this is longer, when it is encrypted, it will become a more complex result.

Then when you compare the "salted password" to a user's password, you just append "SomeSalt" to the user's input. Your condition looks like...

if(COMPARE($_POST['password'] . 'SomeSalt', $db['password'])) {...}

While this was useful at one time, this concept of salting is now built-in to passwords in PHP. You can simply do...

$hash = password_hash($password, PASSWORD_DEFAULT);
if(password_verify($password, $hash) {
// password is valid!
}

This saves you time in coding, and also means that a more reliable, mathematically-based password salt is generated and used.

Source: http://php.net/manual/en/function.password-hash.php

Saturday, August 25, 2018

What values are valid for an ID attribute in an HTML element?

When naming id attributes of HTML tags, you do have some limits.

As stated by the HTML4 specification...

>> ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

Source: https://www.w3.org/TR/html4/types.html#type-id

HTML5 has more-relaxed specifications...

There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.

Source: https://www.w3.org/TR/html5/dom.html#element-attrdef-global-id

Friday, August 24, 2018

How to Detect the Character Set Encoding of a MySQL Database

You may want to know if your MySQL DB is encoded in latin1 or UTF-8, or maybe some other charset.

You can see the default character set encoding and collation with these commands...

SELECT @@character_set_database;
SELECT @@collation_database;

But this is just for the current database. There are various other default encodings and collations at different levels, which you will only be able to see with commands like these...

show variables like 'char%';
show variables like 'collation%';

If you want to see the encoding for a particular table, you can find its encoding with...

SHOW CREATE TABLE MyTable;

To see ONLY the encoding of a particular Table's field, you can search the INFORMATION_SCHEMA tables...

SELECT COLLATION_NAME
FROM information_schema.columns
WHERE TABLE_SCHEMA = 'MySchema'
AND TABLE_NAME = 'MyTable'
AND COLUMN_NAME = 'MyField';

Thursday, August 23, 2018

Full UTF-8 Web Application Development - How to Do It Right

With UTF-8 support, you can be guaranteed that any language will work with your code. But there are two fundamental things that you need to make sure happens:

First, convert your database to UTF-8. This is the data part of it.

To convert your database requires changing the default settings and converting the tables themselves. You can change the default settings with...

MyDB@sys mysql> ALTER DATABASE MyDatabase DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;

And you can convert your tables with...

MyDB@sys mysql> ALTER TABLE MyTable DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
MyDB@sys mysql> ALTER TABLE MyTable MODIFY MyColumn VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '';

Second, send all web pages with a UTF-8 header. This is the networking part of it.

For example, in PHP, to send the UTF-8 header, you will run this command being sending any output to the browser...

header('Content-type: text/html; charset=utf-8');

Every program, protocol, etc., has its exceptions and variations, so these are just the two basics you need to handle.

Wednesday, August 22, 2018

"bind_param() expects parameter 1 to be resource, boolean given" -- Possible Fixes?

Your MySQL and PHP code may be fully and logically thought-out. You may have even tested and verified it worked. But now you have this error:

"bind_param() expects parameter 1 to be resource, boolean given"

Your code probably looks something like this...

$db_link = new mysqli($hostname, $username, $password, $database);
$sql = "SELECT * FROM SomeTable WHERE id = ?";
$statement = $db_link->prepare($sql);
$statement->bind_param($_POST['id']);

How do you fix it? The problem is not with the bind_param() function, it's with the prepare() or the mysqli() functions!

If statement is a boolean, that means it is true or false, and in this case, false means that either mysqli() could not connect to the DB, or that prepare() had a problem.

If mysqli() has a problem, it could be a bad username/password combination, a networking issue, a bad db name, or something else. If prepare() has a problem, it could be a bad query, an unescaped term in the query, or something like that.

You can verify that mysqli() worked, by displaying its result and seeing that it's not false, and similarly with prepare().

Tuesday, August 21, 2018

Should Or Shouldn't I Use the MySQL_* functions in PHP?

There are a number of ways to access your MySQL server from PHP.

The first way, and the one originally taught, was to use the specialized MySQL functions in PHP, such as mysql_query(), mysql_connect(), and mysql_real_escape_string().

However, there are two problems with this function set.

First, it uses escaped strings, which are ultimately unsafer, slower, and less reliable than using Prepared Statements in MySQL.

Second, the developers behind the MySQL_* functions are no longer developing it, they no longer accept feedback on it, and they ask users to move onto something more reliable, with Prepared Statements, for MySQL uses.

This second reason is so strong, that all MySQL_* functions have been removed from PHP version 7.0 and up. Learn to do prepared statements, or these two reasons will perpetually haunt your code.

Monday, August 20, 2018

How do I prevent MySQL Injection with PHP?

We all know that you can make a simple form with some HTML, put together a quick PHP script, build a few MySQL tables, and you have yourself a full, working application in a matter of minutes.

Your PHP may end up initally looking like this...

$sql = "SELECT * FROM SomeTable WHERE id = " . $_POST['id'];

The HTML script would contain the necessary form and input elements, and SomeTable would be in the database. But this creates the possibility of a MySQL injection.

To prevent mysql injection, we send the SQL query and user input in SEPARATE statements, called Prepared Statements. Put a question mark where you want the variable to be...

$db_link = new mysqli($hostname, $username, $password, $database);
$sql = "SELECT * FROM SomeTable WHERE id = ?";
$statement = $db_link->prepare($sql);
$statement->bind_param($_POST['id']);

This will prevent users from submitting malicious data. Imagine, for example, if someone tried to submit an 'id' of value "0 AND DROP TABLES;", which would have a negative consequence on your app.

Sunday, August 19, 2018

How to Wrap Text in Pre-Tags in HTML

You can use PRE tags to make text look like code in most computer terminals, which is a monospaced, Courier font.

But the problem with PRE tags is that the text does not wrap automatically. If the user wants to see a long paragraph, they need to scroll RIGHT on their computer screen, instead of DOWN, which is more intuitive.

To make PRE tagged text autowrap, the code is very simple...

pre {
white-space: pre-wrap;
}

All PRE-tags are now wrapped. This solution will work on all modern browsers.

If you want a solution that works on older machines, the code is a bit more complex...

pre {
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}

(Multi-Browser Solution Source: https://longren.io/wrapping-text-inside-pre-tags/ )

Saturday, August 18, 2018

MySQL Limit Pagination is Slow on Large Offset Quantities - How do I resolve?

With MySQL field indexing on fields you regularly use in WHERE clauses, you can speed up your performance.

You can also use LIMIT to either limit your results, or to get paginated results. If you show 20 results per page and you want page 7's results, you would select with...

MyDB@sys mysql> SELECT * FROM ... LIMIT 7, 20;
...
20 rows in set (0.01 sec)

But this query becomes intensely slow with higher offsets, such as this query...

MyDB@sys mysql> SELECT * FROM ... LIMIT 50000, 20;
...
20 rows in set (0.35 sec)

The same exact query, using different offset limits, has very different performance!

But it is very easy to get around! Just use a subquery to select the id's first, which has your LIMIT.

MyDB@sys mysql> SELECT * FROM ... WHERE id IN(SELECT id FROM ... LIMIT 50000, 20);

Bypassing this problem shouldn't really work, and yet it does! That is because this has been a bug with MySQL for about the past decade: https://bugs.mysql.com/bug.php?id=41871

Friday, August 17, 2018

How do I remove a MySQL Index on a Table and Column?

MySQL indices can make your DB faster, but at times, you may need to remove them, for instance, when they are no longer needed or when a compound index is more appropriate.

For a MySQL DB named MyDB, you can remove a table index with...

MyDB@sys mysql> DROP INDEX `SomeIndexedColumn` ON `MyTable`;

Then, you can verify that this change took place, by showing the indices on the table afterwards...

MyDB@sys mysql> SHOW KEYS FROM MyTable;

Then you can proceed to add the indices or compound indices that your table needs.

Thursday, August 16, 2018

MySQL is Not Using Index Key on Field - How do I resolve?

If you need to speed up your MySQL DB, you're adding indices on your columns. You will see a massive, immediate improvement in performance.

But sometimes you won't, and there are a number of ways to diagnose and resolve those problems.

1) Run the Analyze command on the table. For instance...

MyDB@sys mysql> ANALYZE `MyTable`

This tells your MySQL storage engine to look at the possible ways to join or select this table.

2) MySQL is using a different keys than the one you specified indices for. If your where clause is on multiple statements, you may want a compound index to make it more clear to the storage engine...

MyDB@sys mysql> ALTER TABLE `MyTable`
ADD INDEX `ComboIndex` (`Column1`,`Column2`)

And this will work with...

MyDB@sys mysql> SELECT .... WHERE
Column1 = "ABC" OR COLUMN2 = "DEF";

3) Your query may be simply too complicated for MySQL to grasp. In this case, simplifying the query into multiple UNION'd statements will produce the desired output at amazing speed...

MyDB@sys mysql> (SELECT .... WHERE
Column1 = "ABC") UNION (SELECT .... WHERE COLUMN2 = "DEF");

Wednesday, August 15, 2018

How do I add a MySQL Index Key to Improve Select Performance?

If you have a MySQL database, you can improve performance by adding index keys.

Indexing makes it so that SELECT statements will execute faster, when you have a WHERE clause that uses an indexed key. The speed different can be insignificant (on small DB's), or tremendous (on bigger DB's).

Add a MYSQL index to a column like this....

MyDB@sys mysql> ALTER TABLE `MyTable` ADD INDEX `MyColumn` (`MyColumn`);

Then you will get better performance with statements like...

MyDB@sys mysql> SELECT * FROM MyTable WHERE MyColumn = 'SomethingIWant';

You can also verify the keys a table has with....

MyDB@sys mysql> SHOW KEYS FROM MyTable;

Or, even with this....

MyDB@sys mysql> SHOW CREATE TABLE MyTable;

Tuesday, August 14, 2018

How do I list all tables in a MySQL Database?

If you have a MySQL database named MyDB, you can see all of the tables with...

MyDB@sys mysql> show tables;

If you have a bit more time, you can see all the tablenames for just the current DB with...

MyDB@sys mysql> select TABLE_NAME from INFORMATION_SCHEMA.tables WHERE TABLE_SCHEMA = 'MyDB';

Or, if you want to see all tablenames for all databases in MySQL, you can run this....

MyDB@sys mysql> select TABLE_SCHEMA, TABLE_NAME from INFORMATION_SCHEMA.tables;

You're now on your way to seeing all the database information.

Monday, August 13, 2018

How to Fix Getting Errcode 28 on MySQL?

Query3 failed: Error writing file '/tmp/MY9uc2x7' (Errcode: 28)

If you are seeing this error, it is not a MySQL Error Code, but a Linux OS Error Code.

See the full message with the C++ debugging tool, perror:

perror 28

And this will output:

OS error code 28: No space left on device

So the problem is easily solved! Delete some stuff on the server hosting your DB.

Monday, August 6, 2018

How to Grep files in Linux, but only certain file extensions?


Want to search your file system on Linux?  It's easy!

    grep -r --include=\*.txt 'searchterm' ./

...or case-insensitive version...

    grep -r -i --include=\*.txt 'searchterm' ./
  • grep : command
  • -r : recursively
  • -i : ignore-case
  • --include : all *.txt: text files (escape with \ just in case you have a directory with asterisks in the filenames)
  • 'searchterm' : What to search
  • ./ : Start at current directory.