Referential Integrity and Foreign Key Constraints in MYSQL

I am writing this tutorial to explain some of the basic concepts of referential integrity using foreign key constraints in mysql.

Referential integrity simply means that when a record in a table refers to a corresponding record in another table, that the child record will be acted on accordingly.

Another definition that you might find usefull is that of a foreign key. A foreign key is a field that matches the primary key in another table.

A simple example to illustrate this is the parent record with multiple child records. Lets say a parent record has three child records. This means that all three child records belong to the parent record and are associated to the parent record via some key, usually a foreign key. Without referential integrity, if the parent record were to get deleted, the child records would become orphans because they dont belong to any other parent.

Obviously, you could delete any child record with your application but this can get messy. Plus, developers sometimes forget the schema of a database and the relationship between tables and tend to forget to remove or update child code. This is where Foreign key constraints come in.

Foreign key constraints, in so many words, basically states that whatever action is defined on the parent record, must be taken on the child. To continue with our example, say that we now have foreign key constraints in our tables and we want to delete the parent record. Because we have a foreign key constraint that states, sudo code, that if the parent record gets deleted, then any child record shall be deleted as well. This will prevent having orphan records in the database, which over time can increase the number of records plus having records that aren’t associated with any other record in the database.

Now, for more concrete examples. Lets create a few tables:

mysql> CREATE TABLE Parent
-> (
-> ParentID SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
-> Name VARCHAR(40) NOT NULL,
-> PRIMARY KEY (ParentID)
-> );
Query OK, 0 rows affected (0.02 sec)

mysql>

mysql> CREATE TABLE Child
-> (
-> ID SMALLINT UNSIGNED NOT NULL PRIMARY KEY,
-> ParentID SMALLINT UNSIGNED NOT NULL,
-> Description VARCHAR(40),
-> FOREIGN KEY (ParentID) REFERENCES Parent (ParentID)
-> ON DELETE CASCADE ON UPDATE CASCADE
-> );
Query OK, 0 rows affected (0.05 sec)

Obviously this is a very simple example but yet very powerful. The focus on the two tables you just created should be on the “Child” table. The rule you just added in the Child table is
“FOREIGN KEY (ParentID) REFERENCES Parent (ParentID) ON DELETE CASCADE ON UPDATE CASCADE”.
Let me explain what this doing. The first part basically says that the foreign key in the child table is “ParentID”. This is the primary field for the Parent table. So the child record is always associated with the Parent record based on the ParentID. The next part of the rule states that it “REFERENCES Parent” or the Parent table and the ParentID column. Finally, the last section states that if the Parent record is deleted, then the child record will be deleted and this should “CASCADE” down to any other child records associated with the Parent. The same concept applies to the “ON UPDATE CASCADE”. If the parent record is updated, then the child record should also be updated.

TIP: You should always let the database do the deletes and updates between associated records. This will keep referential integrity in your database and also will keep your database clean.

IF YOU NEED TO SEE FOREIGN KEY CONSTRAINTS on your database, execute the command SHOW CREATE TABLE tablename.

If you need to add a foreign key after you have create the table, using our example, you can do the following:
ALTER TABLE Child ADD CONSTRAINT FK_parent FOREIGN KEY (ParentID) REFERENCES Parent (ParentId) ON DELETE CASCADE ON UPDATE CASCADE;

If you need to drop the foreign key rule, use the following command:
ALTER TABLE Child DROP CONSTRAINT FK_parent;

If you have any questions at all on this topic, please don’t hesitate to contact me.

Updating Parent Page From Child Page

Updating the parent page from the child page using javascript, is a very straight process. I have outlined very simply the steps below:

In this example, I am going to post data back to the parent from the child page.
In order to set the post parameters you would like posted to the page, set your variables first like so

window.opener.document['formName'].variableName.value=theValue

This bit of code basically sets the variableName with a specific value on the parent window. Once you have done this for all the variables you need to post to the page, you want to submit the variables. This can be accomplished with:

window.opener.document.formName.submit();

If you need to refresh the parent window from the child, just use window.opener.reload().

A very simple way to post data to the parent.

Mysql Load & Exporting Data

Looking for ways to export or import data from mysql?

If you are interested in importing data but you don’t want to import the structure of the data, you can export data to a csv file and then re-import the file into the database by loading the data file.

IMPORTING DATA FROM CSV FILE (MYSQL):

LOAD DATA INFILE ‘/file/location/file’ INTO TABLE tablename FIELDS TERMINATED BY ‘,’ LINES TERMINATED BY ‘\n’ (field1, field2, field3);

Fields can be terminated by tab ‘\t’ or a single quote ‘\” or a double quote ‘\”‘. Although I highly recommend that you use either commas or tabs. Using other delimiters may cause you some headaches with the right situation in the future.

If you don’t need quotes around all fields (e.g. numeric fields) then change “ENCLOSED BY” to “OPTIONALLY ENCLOSED BY” and MySQL will only put quotes around the fields that need them. Some systems require all fields in a CSV file to have quotes around them so you may need to export the data with quotes around them all depending on your requirements.

EXPORTING DATA INTO CSV FILE (MYSQL);

SELECT * INTO OUTFILE ‘/file/location/file.csv’ FIELDS TERMINATED BY ‘,’ LINES ENCLOSED BY ‘\”‘ LINES TERMINATED BY ‘\n’ FROM tablename;

If you require only specific fields to export, replace “*” with the fields. For example: SELECT field1, field2, field3 INTO OUTFILE…

If you get an error like:

#1 – Can’t create/write to file ‘/tmp/products.csv’ (Errcode: 13)

It’s possible that you don’t have the proper permissions to write to the directory or that you have a file with that name already there. You will not be able to overwrite the file if it does exists.

Dump data and table to a file

mysqldump -u user -p database table > filename
Example: mysqldump -u someuser -p database table > filename.sql

Dump the entire database

mysqldump -u user -p database > filename

Dump table structure and no data

mysqldump -u user -p -d database table > filename.sql

Yamaha 1100 Two Stroke Motor Needed

I have a two stroke 1100 (jet ski) motor out of a 1996 wave venture ski that I had in my XL700. Motor ran great till the other day. Unfortunately for me, the motor through a rod and broke the side of the block and now it is no longer a running motor ….lol :=(

I am now looking to replace the motor.

If you are interested, here is what is left of the motor:

As you can see, there is a nice gaping hole in the side of the block (middle pic) where the bearings just left and the rod was on its own…

So here is what I am looking for.

If you have parts for this engine, have a motor sitting around, or have any engine parts that you think you might want to sell, please contact me. I am willing to purchase parts if they are in good shape and priced right.

I need a full motor or crank, block (mid section).

Also, I am interested to hear if you have ever dealt with the companies SBT Engine Parts and Accessories or PWC Engines company.

Thanks

Fedora 15 Geany IDE Error renaming temporary file: Operation Not Permitted

Geany is a light weight IDE for Linux. When using with a mounted file system, please see the article on “Mounting Remote File System”, it may give an error stating “Error renaming temporary file:Operation not permitted”.

In order to fix this, you will need to pass an additional flag when mounting the file system.

Instead of mounting the file system like so:
sshfs remoteuser@remoteserver.com:/home/remoteuser/blah /home/localuser/blah
You can do it like
sshfs -o workaround=rename remoteuser@remoteserver.com:/home/remoteuser/blah /home/localuser/blah

Mounting Remote FIle System (IDE USAGE)

First let me say that many of these blog posts are here for my information as well as yours.

Going from a Windows Desktop environment to a Linux (Fedora) Desktop environment has its challenges. Going from the knowing to the unknown always involves a learning curve.

Whether you are a power user or web-developer, it makes no difference. You have reason to be able to connect to a remote system via SSH, or FTP to make changes to files. Many of us, not including myself any longer, use applications like SecureCRT to ssh directly into the server and use VIM to manipulate the files. Possibly we might use Zend Studio IDE and use their built in SSH/FTP to connect to the box to edit the files. Whatever method you are using on Linux, Unix there is a easier way.

REMOTE FILE SYSTEM MOUNTING!!!!

To connect to a remote file system securely, you can use sshfs and fuse together. Fuse is a command used to mount remote file systems encrypted through SSH.

Doing so, will allow you to modify files as if they were an additional drive on your system.

First, remember this only applies if your desktop environment is a Linux environment and NOT WINDOWS.

The packages that you will need are listed below:

1. sshfs
2. fuse-utils

These are the commands needed for the different types of packages. Also, you will need to be root in order to do these following steps.

STEP: 1

Debian:
apt-get install fuse-utils sshfs
Ubuntu:
sudo apt-get install fuse-utils sshfs
Fedora and Centos:
yum install fuse-utils sshfs
Mandriva: urpmi:
urpmi fuse-utils sshfs

STEP: 2
mount the fuse module

modprobe fuse (As usual, if Linux doesn’t complain when issued this command, then everything went fine)

STEP: 3
Create the mount point.

mkdir /mnt/remote-filesystem (This will just create a directory on the file system that will allow you to access the mounted file system as if it were available locally)

STEP: 4

chown user:user /mnt/remote-filesystem/

STEP: 5
Add yourself to the fuse group

adduser user fuse

All these steps should have been done as root.

Now, switch to the user that you are normally, I am assuming that you are not root all the time. Rather, I should say switch to the user that you bound to the fuse group.

HOW TO CONNECT TO THE REMOTE SYSTEM

sshfs remote-user@remote.server:/remote/directory /mnt/remote-filesystem/

This command explained:
sshfs – filesystem client based on ssh.
remote-user – the user you want to login as on the remote system.
@remote.server – the domain name or ip-address of the remote system.
:/remote/directory – the directory on the remote system that you would like to mount.
/mnt/remote-filesystem – the directory on your local box that you would like to point to the remote file system.

Once you issue this command, you will get a warning asking you to accept the key to connect to the server using ssh and then the password.
Upon being connected, you can cd to the /mnt/remote-filesystem directory and do a ls -ls and you will see that now you have access to the files on the remote system as if they were on your local machine.

One thing to keep in mind is that if your connection to the remote system is slow, file browsing and refreshing will be slow.

Once you are done with this feature, you can unmount the directory as follows:

$fusermount -u

for example, in my case, I would use
$fusermount -u /mnt/remote-filesystem

If you happen to get the following error:
fuse: bad mount point `/mnt/remote-fs/’: Transport endpoint is not connected
You will have to use the fusermount command as listed above and try reconnecting

Any questions or concerns, please let me know.

Fedora 15 Top Shell Extensions

I recently converted to Fedora 15.  I have been a Unix/Linux user for a very long time but at the server level.  I have never really given it much thought as a desktop.  However, recently I made the switch on one of my laptops and I liked it sooo much, that I decided to start converting all my hardware over to Fedora.  Yes, I have left Windows and moved on to something fresh and new.

If you are like me, and you are pretty new to the Fedora Desktop world, well I have compiled a list of my top shell extensions.  If you are wondering what are shell extensions, let me explain.  The gnome shell extensions are considered subpackages of the main gnome shell.  Each shell extension has its own purpose or functionality.  So for example, to add the functionality where you can alternate between windows, you would install the sub-package of gnome-shell-extension-alternatetab.  Once install, it will give you the ability to alternate between windows.

Now that we have a very basic understanding of what these shell extensions are, we can move on to explain the most useful ones I have found:

1. gnome-shell-extensions-alternative-status-menu – provides the the restart, shutdown and hibernate option on the user menu on the right.  Without this extension, there would only be the ‘suspend’ option.

yum install gnome-shell-extensions-alternative-status-menu

2.  gnome-shell-extensions-places-menu – provides a menu of all available icons for the user such as Desktop, Documents, Music, Pictures and many more… at the right hand corner of the screen.  Very useful if you would like to have the shortcut available.

yum install gnome-shell-extensions-places-menu

3. gnome-shell-extensions-alternate-tab – this feature provides the ability to Alt-Tab between windows.  This is the same functionality as Windows version where it will allow you to alt-tab between windows, the difference is that if there are any similar windows or child windows of any specific program, you will have to arrow-down in order to access the child windows.  Very helpful and a great feature.  I have notice that this functionality along with others sometimes tends to crash the shell.  I don’t have specific information on this elusive bug since it doesn’t happen very often and sometimes not at all.

yum install gnome-shell-extensions-alternate-tab

4. gnome-shell-extension-autohidetopbar – automatically hides the top bar until you hover your mouse over that part of the screen, essentially providing more real estate on your desktop.

yum install gnome-shell-extension-autohidetopbar

These are just some of my favorite shell extensions for Fedora.

HTC Wildfire S Unknown State of SD Device

Recently I purchased a new HTC Wildfire S phone.  First let me say, great phone! Obviously the operating system is amazing and there are plenty of applications to choose from.

Overall, I am extremely happy with the phone.  I did run in to one issue, because I am a new user of the phone, that took me sometime to figure out.  I was in the process of trying to take a picture and every time I clicked on the shutter button, it would act as if it was going to take the picture and would not.  What I didn’t noticed is that the sd card had a exclamation mark next to it.  When I looked at the notification, I noticed that it had an error, which read “Unknown state of sd device”.    This caught me by surprise because I had recently purchased an 8Gig SD card and placed it in the phone.  No problems at all detecting it.  So it seemed strange that all the sudden it couldn’t detect the card.  Here is what I did in order to get this working if you have run into the same issue:

  1. Go to All Apps and click on settings
  2. Than click on SD & phone storage.  ( we will check to see that the card is unmounted).
  3. If it is not unmounted, then click unmount SD card.  If it is unmounted, then you dont have to do anything at this point.
  4. Turn the phone off by holding down the power button on the top of the phone.
  5. Remove the back cover by removing from the top of the phone.
  6. Grab the SD card and pull it out.  IT should be on the side of the phone.
  7. Insert the card back into position and make sure that it is seated well.
  8. Restart your phone.
  9. Then go through step 1 through step 3 and check that the card is mounted.  If it is not, then mount the card.  If the card fails to mount, then you will get the same notification again.  This usually fixes the problem, but if it doesn’t try using a different sd card to see if the initial one is damaged.
This is basically what I did in order to get my SD card working on my phone.
Oh, and try and not make the same mistake I made, which is confusing the Sim card with the SD card.  Your Sim card is located behind the battery, while your SD card is located on the side of the phone.

Automatic Searching of Craigslist and other services

http://www.yominder.com

Finding the things you want on Craigslist can be a miss or hit.  Its been my personal experience that most of the time I find what I am looking for to only find out its been already sold or given away.

I have created a web application that will notify you when an item you are looking for on craigslist is advertised.  Its functionality is very simple but yet can be very powerful. Here is how it works.  The idea is that you can enter a search about a specific item and it will search for you.  Say you are looking for a wooden table.  The normal process of searching on Craigslist would require you to log on to Craigslist services everyday once or twice a day and run your search.  This is not always possible as most people have work, kids, and other events that might keep them from logging on.  So, here comes YoMinder.com to the rescue.

Usage is very simple.  You will have to log into the service as an account is required. Otherwise how would we notify you?  The account creation itself only consists of a few fields; Your first name, last name, email address, and password.  You can enter an SMS number but that is optional.  Yes it will even send out SMS messages so that you can get notified even faster.

Searching Steps

  1. Create a search by clicking on the “Add Searches” link from the menu.
  2. Choose the service that you would like to run. Some of these services include autotrader, monster,  careerbuilder, and realtor.com.
  3. Enter the appropriate fields.  These fields will vary according to the service so just complete all fields as much as possible.
  4. You are done.

So what happens next?  Now the search will be added to the system.  It will pickup your search and run the initial search for you.  You will get an email within a few minutes notifying you of results.  Once the initial search is done all you have to do is sit back and wait for the system to search for you.  The system will search three times a day for you but will only pickup the new results and send you and email or an sms.

Its that simple.  If you are interested in using this system, remember this is FREE.  There is no charge for this or any obligation.  Enjoy!

http://www.yominder.com