Tag Archives: php

4 PHP Security Pitfalls to Avoid

For PHP developers of both newbie and veteran status, there are always new ways in which hackers exploit our carefully-crafted scripts. We have to keep tabs on newly discovered security holes in our scripts, as well as minding how we construct our pages so that people can’t just inject a bunch of code into our websites, all so that our sites will run the way we want them to, and so our users’ data will be protected.

Thus, I bring to your attention the following 4 PHP pitfalls, which are vitally important for us to be aware of as we build our sites. (Incidentally, this post started out as a “PHP tricks” post, but when I saw just how many blog posts are out there already with that premise (and how many of them advocate unsafe code), I thought it best to research PHP security problems instead. And boy, did I ever discover some doozies!)

#4: Exposing Your Filepaths to Users

Most users won’t care much if the paths to various files on your site are easy to guess (or easily viewable in their address bars). A few users, however, may choose to take advantage of that–not just for hotlinking your images, scripts, etc., but for stealing data that is supposed to be secure! Yikes! If you’re running any kind of site with
logins and passwords, especially an e-commerce site, easily-visible filepaths are BAD!

So, how to fix this? Thankfully, there are fairly easy PHP scripts that can disguise a file’s real path on your server with variables, making it much more difficult for hackers to guess where a file is. For instance, motov.net has an example script that is only 13 short lines of PHP code!

#3: Not Securing Your Databases

As mentioned in #4, MySQL databases with logins, passwords, credit card info, etc. are very juicy targets for hackers. If you don’t build in protections for all this sensitive data, your site could end up being victimized, leaving you with very angry users!

PHP.net has a series of articles on how to design your database for better security, how to securely connect to such a database, and more. Layering database security, just like layering clothes before you go out in the cold, can really help protect your users’ data! (Also, WebmasterWorld’s forums has a post about securing database connections which may be of further use.)

#2: Leaving Your PHP Sessions Open to Hijacking

Any time you have users logging in to a site, you are most likely incorporating a PHP session ID, a unique number that tracks them around the site so they don’t have to keep logging in every time they go to a new page. Unfortunately, hackers can get hold of those numbers if they’re easily guessed or stored in an insecure location (see #3). You might not think somebody could wreak much havoc with just a PHP session ID number, but a hacker could end up stealing somebody else’s whole account with just such a number!

To keep your users’ session ID numbers safe(r), consider some of the tactics suggested on this StackOverflow topic, including SSL connections, randomly-generated ID numbers (instead of incrementally increasing numbers), and sessions that expire within shorter time frames.

#1: Leaving Your Site Vulnerable to SQL Injections

When we PHP developers, especially newbie developers like myself, write MySQL queries pointing to our databases, sometimes we forget that malicious users exist for a minute. We forget to keep our very PHP script files safe from “SQL injections”–that is, targeted code attacks that fiddle with our SQL queries just enough to dig up data from the database, rewrite it, or even delete it all!

To keep your SQL/MySQL code from being fiddled with or just plain overridden, PHP.net has an excellent reference article which explains several code tactics you can use, such as connecting to your database with a user specifically limited to the task you’re trying to complete, checking that the inputted data is the right type, etc. This StackOverflow topic about preventing SQL injections may also be helpful as you tackle this tricky issue.


All of these precautions may seem unnecessary, especially to newbie PHP developers, but these are all giant security holes that can cause us a lot more headaches and frustration (not to mention user anger). Nip these problems in the bud, and you’ll be saving yourself a lot of time and trouble later!

Oh, the Things PHP Can Do!

Since I’m largely self-taught in all things webdesign, PHP can be both frustrating and magical, a box full of wondrous tools I know neither the origin nor the use of. If you’re a newbie developer like me (or even if you’re somewhat familiar with PHP), you’d be surprised how much PHP can accomplish for your website these days:

Collecting Feedback

This article at CodeTricks.com explains how to make a really simple feedback form, which emails you comments and questions that people have submitted. (This tutorial covers both the HTML form part and the PHP part, so I find it VERY informative!)

Displaying Thumbnail Photos in a Gallery

Nettuts’ article covers one way to easily display photo thumbnails with a few lines of PHP code–much better than having to host your photos on another site, or worse, making an HTML table for your images and resizing all your images yourself. (Been there, done that :P) Scroll down to #12 on Nettuts’ article to find out more!

Making Easy Site Templates

This PHP article at About.com shows you how to use a PHP header and footer to create a site template, which you can change easily by editing the content of just those two files. (I use this trick on almost all my sites–it makes my webdesigning life SO much easier!)

Automatically Sending Mail to a Mailing List

Nettuts also covers how to use PHP to send mail to a specific list of people–who knew there was such an easy way to automate it? (Just scroll down to #8 on their article to see more on how to code this.)

Redirecting Your Visitors to Your New Page

Need to redirect your users to your new page without requiring them to click another link? Over at About.com, they show you how to use just a line or two of PHP code on a mostly-empty page to get it done! (I had no idea it was this easy! WOW…)

Creating Your Own Content Management System

This post at CSS-Tricks.com shows you how to set up a MySQL database, make a specific table for posts within that database, make a simple submission form so you can add posts, and display posts using PHP on a webpage. Basically, it shows you how to beat blogging websites at their own game! (Can be a little technical in parts, but it has links to other articles for extra explanation)


Can you believe PHP can handle all this–and more? I sure didn’t, until I did research for this blog post and realized just how much PHP can help us webmasters with our tasks. Try implementing one or more of these techniques for your site, and see how much time it can save you!

The 5 Web Languages You Need to Know

Much like learning a language is for communicating with other humans, creating websites from scratch is all about communicating your design and function intentions to a browser or Web server. And to be a good web developer in this day and age, you need to be multi-lingual–speaking several different programming languages to be able to design better, sleeker and more functional websites.

But just Googling “web programming languages” or something similar brings up a whole host of options to learn, and it can be overwhelming for the beginning user. Where do you begin? Do you start learning MySQL, or Ruby on Rails? Should you take a course in HTML, or is Python the next big thing?

Thankfully, it doesn’t have to be this confusing. In this post I have culled the 5 most important Web programming languages to know–the ones which make up about 90% of most modern websites. If you’re just beginning to learn how to build websites, this article will serve as a road map.

HTML: The Skeleton of the Web

HTML is the strong, silent (and mostly invisible) foundational structure which provides you a page to look at (such as the one you’re reading from right now). It provides line breaks, breaks text up into paragraph structures, formats tables, divides page content into layers…pretty much anything that makes up your page’s most basic structure is what HTML handles best.

This should be your first Web language to learn, since so many of the other programming languages depend on it to function. Here are some excellent resources to start learning:

HTML Tutorial @ W3Schools.com
QuackIt.com’s HTML Resources

CSS: The Magic Styling Wand of the Web

Perfectly complementing HTML’s invisible strength, CSS takes HTML’s structure and gives it style. From giving your text just the right font choice and color to aligning each of your divided layers pixel-perfect on the screen, CSS can transform any boring old text and images into a lovely yet still functional page. There are plenty of simple CSS tricks that translate into downright amazing page effects–things you would never expect to accomplish with just a few lines of code!

CSS should be your second language to learn, as it builds on HTML knowledge while extending HTML’s capabilities of displaying Web content properly. Here are some resources to study CSS (both how it works and what it looks like when done right):

CSS Tutorial @ W3Schools.com
Sitepoint.com’s CSS Reference

Javascript/jQuery: The Swiss Army Knife of the Web

Whatever special function you want your site to perform, whether it’s something to make your site display differently, something to change how your navigation menus open, etc., there’s likely a snippet of Javascript that can make it happen. Just putting a bit of carefully-chosen or carefully-crafted Javascript code into the head part of your HTML document can make a big difference! (By the way, the only real difference between Javascript and jQuery is that you don’t have to have a big library of Javascript code installed on your site for jQuery to work–all you need is a link to the library of code that’s already established on the Internet.)

Javascript should be your third language to learn, as it bridges the gap between Web languages that more about site display (“front-end development”) and Web languages that are more about site function (“back-end development”). Here are a few good websites to start studying Javascript:

Javascript Tutorial @ W3Schools.com
Codecademy’s Javascript Lessons

PHP: The Workhorse of the Web

Many of the websites you see today, like this one, are made possible with PHP–it’s literally everywhere, even though none of its code appears when you click “View Source.” The reason its code does not appear is because PHP is a server-side language, meaning that everything it does is tied to having a conversation with the server (that’s the thing that holds all your web pages, images, etc.).

PHP acts as a go-between for your browser (Internet Explorer, Mozilla Firefox, Google Chrome, or similar programs) and the server, asking questions of the server and delivering appropriate responses back to the browser in the form of a displayed page. (Ever searched for anything using a site’s search box? PHP was likely powering the search!)

PHP should be your fourth language to learn, since it is the most widely used of all the server-side languages, yet still deals with outputting data in HTML/CSS forms. Here are some excellent resources to help you learn PHP:

PHP Tutorial @ W3Schools.com
Tizag.com’s PHP Tutorial
PHP @ HomeAndLearn

MySQL: The Librarian of the Web

If you’ve got data to store, search through, and access, MySQL can handle it quite ably–it’s a programming language built to make, search, and access online databases on a server. The only trouble is, it doesn’t actually display the data on its own. So, quite often you’ll see PHP and MySQL being taught side-by-side; PHP code can “talk” to the MySQL database and retrieve results.

Still, you need to know how MySQL works in order to build a PHP script that can communicate with it. (Believe me, if you don’t know how MySQL works, you’re going to be VERY frustrated trying to build a successful PHP code to work with a MySQL database!) Here are a few sites to start your MySQL learning:

SQL Tutorial @ W3Schools.com
Tizag.com’s MySQL Tutorial

(Fun fact: Most formally-trained programmers pronounce MySQL as “my sequel.” I, however, being relatively untrained, mentally pronounce it “my skwul” despite trying to train myself otherwise. LOL!)


These five Web programming languages may look scary, but if you take them one language at a time, mastering each before you move on, you will find that things become much easier to understand. And, once you understand these five, you will have a great basis of knowledge on which to build even further programming know-how. I hope this little “road map” serves you well!

Commenting Your Code: A Helpful Habit to Start

“Wait, what? You can put things in your code that are not read by the browser? Why would anybody want to do that?”

When I first started learning how to design web pages, I thought the same thing about using comments, until I started going back through my old layouts to rework and revamp old code for new designs. Boy, had I written myself some head-scratchers. “What in the world is THIS div even doing in the code? It doesn’t have anything in it!” “Huh? What’s this weird padding and margin thing?”

At the time I drafted the older bits of code, I knew exactly what I was doing with the code–I knew exactly what purpose each div, margin, spacer image, and line break was for. But going back to that old code after three or four years? Let’s just say I spent a lot longer than I should have trying to decipher my past self’s reasoning. LOL!

So, to avoid this kind of bafflement every time I go back to an old design, I have resolved to start using comments in my HTML, CSS, PHP, and Javascript codes.

Why Use Comments in Your Code?

As I’ve already said, comments are a great way to remind yourself of why you coded a particular section the way you did. (For instance, reminding yourself that a certain div or code hack is only in place to make IE behave itself. There are plenty of instances of that! LOL!)

But comments aren’t just useful for leaving yourself reminders about code–they’re also good ways to section your code, so that you don’t have to hunt through thousands of lines just to find the one thing you want to fix.

For example, an HTML page sectioned out might look like this:

<div id=”nav”>

<div id=”content”>


And a comment-sectioned CSS file might look like this:

body {color: #FFFFFF;
background-color: #000000;

a:link {color: #FF0000; text-decoration: none;}

Both usages are sanity-preserving (and as web developers, we all know that sanity sometimes is in short supply, LOL). Comments make it possible for you to leave reminders, section headers, and even silly little in-progress notes to yourself to make your job a little more fun.

How to Code a Comment, in Four Different Web Languages

Each Web programming language has its own comment tag style, a way to include things that are only for the web developer to see.

HTML Comments

When you want to start an HTML comment, you place “” after. Like the following:

<!–Woo this is a comment–>

Comments in HTML can be placed anywhere within the <body> tag; the browser will just ignore them.

CSS Comments

When you want to comment in your CSS code, just put a “/*” before you start the comment, and put a “*/” at the end, like this:

/* Yay I have some CSS styles, woot */

You can place CSS comments anywhere in your CSS, whether your CSS is in a separate file or in the <head> section of your page.

PHP Comments

There are two kinds of PHP comment styles–one for comments that only take up a single line in your PHP document, and another for comments that take up multiple lines in the document. (In PHP, lines REALLY matter, so if you’re not sure if your comment will only take up one line of code, best to use the multi-line comment.

Single-Line Comment
To put in a single-line comment, just put “//” or “#” before you begin your comment. Everything to the right of those double slashes or hash symbol will be commented out as long as it’s on the same line as the slashes or hash symbol. Like so:

<?php echo “Whee!”; // a simple little echo statement
# why did I just write Whee? xD

Multi-Line Comment
If your comment is going to go for multiple lines, you’ll instead put in “/*” before you begin your comment, and “*/” after you’ve finished your comment. (Looks identical to CSS!) Here’s an example:

<?php echo “Whee!”;
/* Seriously, why did I just write Whee?  I have no idea.
Possibly because it’s 2 AM and I’ve been staring at this code for hours? LOL */

Javascript Comments

Like PHP, Javascript has two different styles of commenting, depending on if the comment is on a single line or multiple lines.

Single-Line Comment
Doing a single-line comment in Javascript is identical to doing it in PHP–you use “//” before your comment, and everything out to the right of those two slashes will be commented out. Example:

<script type=”text/javascript”>
//I need to add some more stuff here!

Multi-Line Comment
Again, identical to PHP (and CSS), Javascript uses “/* at the beginning and “*/” at the end of its multi-line comments. Makes it pretty simple to remember if you code in multiple languages!

<script type=”text/javascript”>
/* Here I’ll put in a few more document.write things, as well as some preloaders, but I need to be careful! */

References and Further Reading

Here are the sites I used to research this article; they are both great sites to help you learn more about web development of all sorts.

HTML Comments @ W3Schools.com
CSS Comments @ W3Schools.com
PHP Comments @ Tizag.com
Javascript Comments @ Tizag.com

PHP Includes: Not Just for Headers and Footers Anymore!

Many of us likely use PHP includes to build and maintain our sites these days. But I would guess that most of us just use the following includes and nothing else:

<?php include(‘header.php’); ?>
<?php include(‘footer.php’); ?>

Headers and footers are very easily managed through the PHP include method. But thankfully, includes are not restricted to just headers and footers–in fact, you can manage a whole site with includes!

Example: My Joined Fanlisting Page

Back before I really mastered PHP includes, I had a joined fanlisting page–literally, it was a PAGE, because it was one single HTML file. Everything–style info, links, image sources–all were crammed into this one file. Uploading new layouts for it didn’t take a long time, but it sure was time-consuming to edit the file in any way. God forbid I would actually have to change a link or an image source!

For a long time, I didn’t know how else to do it; I just kept scrolling up and down in the same huge HTML file, spending countless minutes hunting for the small portion of code I wanted to edit.

And then, I discovered the beauty of including more than just header and footer.

The Solution: Make Each Section into a Different File!

When you visit my joined fanlistings site, it may not look any different to the user, but it’s vastly different on the back-end. Each section of fanlistings is separated out into its own files, as seen below:

As you can see, I have a file for every subject matter: fashion and beauty, food and drinks, movies, characters, etc. This makes it much easier to locate and edit links when needed. All I have to do is look for the general topic of my fanlisting, open the file that corresponds to it, and start editing, no frantic searching required!

This is what each separate file’s code looks like. Each section has its own special divided layer, and all of its code is self-contained so that it all fits within the larger “puzzle” of the index.php file.

Notice that I don’t have to put includes for the header and footer in each of these files–each file is simply a piece of index.php, not a page in its own right like most other PHP-driven sites.

Therefore, index.php is just a list of included files and nothing else, which makes it easy to add or delete a section from the viewable site as needed.

Why Bother Doing This?

I can think of three reasons you’d possibly want to break up your site into small files and including them with PHP:

  • You’ve gotten lost in the code while trying to edit your file
  • Editing your file has become so tedious that you put off doing it
  • The individual file loads more slowly than you’d like

In any of these three cases, breaking your data into chunks with separate files, and then reassembling those pieces with PHP includes, will help with editing time and loading time.

How to Make PHP-Included Files for Your Site

#1: Determine what defines a “section” for your site.

Look at your code, and look at the content you have. How does it divide up into sections? For me, I could divide my content, my joined fanlistings, by what general topic they could be filed under (Movies, Music, etc.).

#2: Copy-paste each section into its own file.

To divide up your file, you’ll need to carefully copy and paste each little section into a new file, and save it as a PHP file.

Warning: Make sure you carry over any formatting or structure that is specific to each section! I initially forgot to copy-paste the Fashion/Beauty section’s opening divided layer tag when I was creating my new joined fanlistings page, and major havoc resulted when I tested the page. xD

#3: Make your index.php file, with code that includes all your new files.

Once you have all your new little files, it’s time to include them! Wrap them all in a big group hug with code like the following:

<?php include(‘header.php’); ?>
<?php include(‘firstsection.php’); ?>
<?php include(‘secondsection.php’); ?>
<?php include(‘sidebar.php’); ?>
<?php include(‘footer.php’); ?>

Save this as “index.php”, then upload and test it. Result: you should have a perfect, much more manageable site! It shouldn’t look any different to your users, but it’ll be much less of a headache for you. 🙂

Puzzling through PHP, Part 2: Making a Searchable Database

One of my longest-held dreams, as a fledgling Web designer and developer, was to make a fully searchable database of some sort. I used to dream about building a link database or directory, but as I became a collector of M:TG cards, I discovered I wanted to create a database of all the cards I wanted to trade instead.

But I didn’t dream about it being possible, especially not with any Web language I knew. Little did I know, PHP and MySQL working together could make my dream come true. And the best part is, you can make a database like this too! See how I managed it, with the steps below.

#1: Create the Database to Search

On your host’s control panel somewhere, you should have a way to create MySQL databases. This short tutorial shows you the generic way to create databases from your web host’s control panel, while this longer tutorial has a little bit more tech knowledge needed, but shows you how to manually set up MySQL username, password, etc.

For any database setup, you have to give the database a name, then make yourself an “admin user” account so you can access it. Lastly, you have to make a table within the database to hold the data you want to put into it. While you’re doing this, do not forget to write all this information down–you will need the database name, your admin username, and your admin password to do anything with your data afterwards.

Sample information:
Database name: mydata
Admin username: helloitsme
Admin password: epicsuperlongpassword
Database table: mydatatable

#2: Upload Your Data

To have a searchable database, you first need to have data. You could go through and manually create a MySQL database and plug data into it using a ton of MySQL commands. Buuuuut there’s a much easier way.

Microsoft Excel pages, or any other spreadsheet program pages, for that matter, can be converted over to .CSV (Comma Separated Value) format. These, when uploaded to your server through phpMyAdmin or another MySQL handling program, help populate an existing database table.

Example: For my Magic: the Gathering trades database, I had several pages’ worth of card data, which I’d spread out into individual worksheets within Excel. To translate all of those into .CSV format, I had to remove the label rows and columns (like “Name of Card,” “Condition,” etc.), and then had to save each sheet as a separate .CSV file. Then and only then could I upload it through phpMyAdmin to populate my created database with data.

#3: Write PHP Code to Search the Database

The following code is an actual example of the code I use for searching my M:TG trades database; of course, the username, password, and database name are not given here, for security reasons, but everything else remains the same. You’ll want to put this database-searching code in a separate PHP file from your HTML file where your search form is.

(By the way, I do not take the credit for making this code in any way–a dear computer programmer friend of mine used his coding skill and fixed the code so that it does work. AT LAST!! LOL)

<?php if ($searching == “yes”) {
echo “<p class=\”heading\”>Search Results</p>”; }
if ($find == ” “) {
echo “Oops!  No search term entered–try again!”;     exit; }
$host = “localhost”;
$user = “helloitsme”;
$pass = “epicsuperlongpassword”;
$db = “mydata”;
$text = $_POST[‘find’];
$con = mysql_connect($host, $user, $pass) or die (“Connection error”);
$sqlDB = mysql_select_db ($db) or die(“Database selection error”);

$find = strip_tags(trim($text));
$find = strtoupper($text);
$query = mysql_query(“SELECT * FROM mydatatable”, $con);
$found = false;

//This loop will select the row and then uppercase the entire entry
while($data = mysql_fetch_array($query, MYSQL_BOTH)){
$updated =  strtoupper($data[‘name’]);
if($updated == $find)    {
echo $data[‘name’].” “.$data[‘rarity’].” “.$data[‘set’].” “.$data[‘condition’].” “.$data[‘amount’].” “.$data[‘color’];
$found = true;
break;    }}
echo “Could not find this card”; mysql_close(); ?>

What Does This Code Mean?

<?php if ($searching == “yes”) {
echo “<p class=\”heading\”>Search Results</p>”; }
if ($find == ” “) {
echo “Oops!  No search term entered–try again!”;     exit; }

This determines whether the search has been sent to the server for processing, and if anything’s been put into the search form.

If the search form has been passed to the server, the value of the variable $searching will be “yes”; the if statement concerning this variable cues the browser to display the heading “Search Results” in anticipation.

If the user didn’t put anything into the search form, but hit Submit anyway, the variable called $find will be empty; the second if statement returns an “Oops” message if this is the case.

$host = “localhost”;
$user = “helloitsme”;
$pass = “epicsuperlongpassword”;
$db = “mydata”;
$text = $_POST[‘find’];
$con = mysql_connect($host, $user, $pass) or die (“Connection error”);
$sqlDB = mysql_select_db ($db) or die(“Database selection error”);

These are some of the necessary variables we’ve defined for this particular script to run: the host’s name, username, and password for the database ($host, $user, $pass), the database selection ($sqlDB), the connection to said database ($con), and what the search term was ($text).

You may not need all of these, but we found that the script ran better when all of these variables were clearly defined for the browser.

$find = strip_tags(trim($text));
$find = strtoupper($text);
$query = mysql_query(“SELECT * FROM mydatatable”, $con);
$found = false;

These four variables have more to do with refining the search terms and running bits of the script.

The first $find variable strips any code from the search term, so people can’t hijack the database using malicious code. The second $find puts the search term all in uppercase letters. Both help the search script run more quickly (and protect the database from the most basic of hacks).

The $query variable executes the actual script’s purpose: searching the database for anything matching the search term. And to be honest, I don’t know what the $found variable is for at this point in the script…all I know is that it makes the script work. (Pathetic, I know…this is where my PHP knowledge is spelled F-A-I-L.)

//This loop will select the row and then uppercase the entire entry
while($data = mysql_fetch_array($query, MYSQL_BOTH)){
$updated =  strtoupper($data[‘name’]);
if($updated == $find)    {
echo $data[‘name’].” “.$data[‘rarity’].” “.$data[‘set’].” “.$data[‘condition’].” “.$data[‘amount’].” “.$data[‘color’];
$found = true;
break;    }}
echo “Could not find this card”; mysql_close(); ?>

This is the bit of the code I understand the least, but my friend’s comment in the PHP script helps a lot. The “while” code begins a looping search through the database, row by row, finding everything that matches the search term.

Once it finds a record that matches, it returns everything about that record–in this case, it finds the name of the card, its rarity, what set it came from, etc. Then the variable of $found gets set to “true” because it found something. If it can’t find anything, however, it just echoes back a “can’t find anything” statement and ends the script.

#4: Plug in the Info for Your Database

Once you’ve got your search code ready to go, all you have to do is plug in your information for the username, password, database name, and table name (for within the database). Make sure you’ve got it spelled exactly right and that the letters are uppercase or lowercase as appropriate! Can’t tell you how many times I’ve mistaken a lowercase “L” for an uppercase “I”.

#5: Test the Search

Now, you need to see if this bad boy works. Type up a quick HTML form to take in your search term, like the one below (again, taken directly from my code).

<form name=”search” method=”post” action=”search.php”>Search for:
<input type=”text” name=”find” />
<input type=”checkbox” name=”name” value=”Name” /> Name of Card<br>
<input type=”checkbox” name=”color” value=”Color” /> Color (White, Blue, etc.)<br>
<input type=”checkbox” name=”rarity” value=”Rarity” /> Rarity (Common, Uncommon, etc.)<br>
<input type=”checkbox” name=”type” value=”Type” /> Type (Creature, Instant, etc.)<br>
<input type=”checkbox” name=”set” value=”Set Name” /> Set Name (Zendikar, M10, etc.)<br>
<input type=”checkbox” name=”condition” value=”Condition” /> Condition (Near Mint, Good, Fair, Poor)<br>
<input type=”checkbox” name=”amount” value=”Amount” /> Amount of Copies (1, 2, 3, etc.)<br>
<input type=”hidden” name=”searching” value=”yes” />
<input type=”submit” name=”search” value=”Search” />

#6: Debug, Debug, Debug, and By the Way—-Debug

This is the most important (and infuriating) part of this database search. My friend and I spent several months (yes, I said MONTHS) debugging this very script because no matter what we did, it just wouldn’t run. The final edits he made to it, which are reflected in this post, finally made it work.

When you’re working on code like this, it’s important to make sure it’s spaced out enough so that you can read it, and that you work on getting each tiny piece of it perfect instead of trying to scan the whole document for errors. For tired eyes, a colon can sure look like a semicolon, and a lowercase “L” can sure look like an uppercase “I”. You have to watch out for the little errors!

Once you’ve caught all the little spelling and mistyping errors, then you need to check to make sure the code’s variables work like they’re supposed to, and that you’re calling functions that actually exist in PHP and MySQL. For this, it’s best to consult the latest Internet references, or forums where experts in coding gather and help all us abject newbs. LOL

If you’ve made sure everything’s spelled right, and all the functions are supposed to run…well, you do like I did and call upon a friend or trusted authority who knows more about how programming languages are supposed to be written and run. Web development involves programming languages just like the rest of computer science, so there’s no shame in asking if you’re like me and frustrated by anything that resembles math. 😛


The code I’ve demo’ed here does work, at least for searching card names. We’re not sure what was blocking it from working before…oh well, that’s web development for you, LOL. (By the way, searching by color, set name, and all the other stuff still presents an error…it’s definitely still a work in progress. But at least the whole page doesn’t vomit an error every time you hit “Submit!”)

And if you try this code and get even more success out of it, tell me about it in the comments! To quote Robert Stack, “YOU may be able to help solve a mystery…” 😀

Puzzling Through PHP, part 1: Give Variables a Value

PHP is a strange animal, as I’ve noted before. And, since most of my webdesign and development experience is self-taught and I’ve mostly worked with front-end design in HTML and CSS, PHP has been more of a frustrating puzzle than a new horizon in my coding skills.

Because of this, I’ve run into a couple of PHP fails in my attempts to teach myself this new language. That story follows!

Problem: Can’t Search My Own Database

I couldn’t understand why my variable-laden code for a simple database search wasn’t working, since I had gotten the majority of the code off a fairly reputable PHP code website, and I thought I’d input all the variables correctly. But the code continued to return an error, saying that the database was not “a valid result resource.”

Debugging with a Good Friend

One of my good friends is a computer programmer by nature, and though he knew little of PHP at the time, he was able to express one of the fundamental truths of PHP in a way I could understand it. “Basically, PHP sounds like a function-based language,” he said. “You tell it things to do–functions–based on the variables and values you give it.”

What this meant to me: if the variable isn’t right, or you haven’t got a way to give the variable any value, you’re in trouble! Certainly I had already run into that problem when I was trying to make the PHP code search the MySQL database; the darn thing just wouldn’t budge, and now I knew at least one reason why.

Solution: You MUST Be VERY Specific When You Work with PHP

Once I finally understood that I had to give PHP a variable’s value before I could ask it to make that variable jump through flaming hoops, one of the main problems in my searchable database became clearer: somehow, one of the variables that related to the database was not being given a correct value. Otherwise, what else could be making the database an “invalid result resource?” (We eventually discovered that the database connection itself was to blame–I had mistyped ONE comma as a period, and the whole code had gone bonkers as a result.)

It may seem like common sense to people who have already mastered PHP and MySQL, but for a non-mathematical person who would have preferred to leave variables back in algebra where they belong, it was a very tough hurdle to jump. Even realizing this small piece of information was a victory.

Whenever you work with a highly technical language like PHP, remember that it is unforgiving of most errors. Double- and triple-check your code, testing it often, to make sure your changes actually work. And please, for the sake of your eyeballs and blood pressure, make sure your database connection works so that your database variable has a proper value!

Next Up: The Triumphant Fixed Database

Thankfully, this wasn’t the end of the story! Head on over to Part 2 of this article to see how we transformed this broken database script into a functioning one! (Samples of PHP code, oh my!)

For More Info:

PHP Variable Explanation @ W3Schools.com (low-tech explanation)
PHP Variable Explanation @ PHP.net (high-tech explanation)

A Jungle of Strange Words: My Forays into PHP and MySQL


My current experience with PHP and MySQL has not been all tiptoeing through tulips. More often, it’s slashing my way through somebody else’s jungle-y code, trying desperately to understand how each part of the code functions, why even the smallest comma or space throws everything off, etc.

I’ve struggled with various projects in the last few years, mostly working on getting PHP to display results from a MySQL database. One of those projects is this very blog, which is now working beautifully after a few false starts. The other, a Magic: the Gathering trades database, never would find search results the way it was supposed to despite hours of debugging and reworking. (I finally got tired of struggling with it and screaming at it after about a YEAR–I was never so happy to hit the Delete button in my entire life.)

The Problem I Face (and What Most Newbie Programmers Face)

The bottom line is that PHP and MySQL are two of the more logic-based, technical Web programming languages out there. It has been far more difficult to teach myself PHP and MySQL than it was to teach myself HTML and CSS, because the vocabulary is so different, and the syntax is hard to read. From this newbie’s perspective, some of PHP and most of MySQL just hasn’t made sense at all; it’s just dollar signs and semicolons everywhere, and thus debugging it is a lost cause (as I discovered).

More experienced programmers might ask, “Well, why not just Google it and learn from tutorials?” There’s a problem with most tutorials available on the Internet; they are simply not written for actual programming newbies. They contain far too many technical words that are not easily defined–terms that someone with experience would know right away, but which a complete newb to programming would be confused by.

But Never Fear! Help Is On the Way!

Thankfully, after much, MUCH searching, I have discovered a few simpler, well-paced and fully-explained tutorials available to PHP and MySQL newbs like myself:

In some of these tutorials, I have found long-searched answers to some of the most basic MySQL and PHP questions I’ve had–questions which undermined any knowledge I tried to take in. With those now answered, I think I’m finally on my way to understanding. Check them out, and see if these careful explanations work for you!