Tuesday, March 4, 2008

MySQL Database Handling in PHP

Most interactive websites nowadays require data to be presented dynamically and interactively based on input from the user. For example, a customer may need to log into a retail website to check his purchasing history. In this instance, the website would have stored two types of data in order for the customer to perform the check the customers personal login details; and the customers purchased items. This data can be stored in two types of storage flat files or databases.

Flat files are only feasible in very low to low volume websites as flat files have 3 inherent weaknesses:

  1. The inability to index the data. This makes it necessary to potentially read ALL the data sequentially. This is a major problem if there are a lot of records in the flat file because the time required to read the flat file is proportionate to the number of records in the flat file.

  2. The inability to efficiently control access by users to the data

  3. The inefficient storage of the data. In most cases, the data would not be encrypted or compressed as this would exacerbate the problem no. 1 above

The alternative which is, in my opinion, the only feasible method, is to store the data in a database. One of the most prevalent databases in use is MySQL. Data that is stored in a database can easily be indexed, managed and stored efficiently. Besides that, most databases also provide a suite of accompanying utilities that allow the database administrator to maintain the database for example, backup and restore, etc.

Websites scripted using PHP are very well suited for the MySQL database as PHP has a custom and integrated MySQL module that communicates very efficiently with MySQL. PHP can also communicate with MySQL through the standard ODBC as MySQL is ODBC-compliant, However, this will not be as efficient as using the custom MySQL module for PHP.

The rest of this article is a tutorial on how to use PHP to:

  1. Connect to a MySQL database

  2. Execute standard SQL statements against the MySQL database

Starting a Session with MySQL

Before the PHP script can communicate with the database to query, insert or update the database, the PHP script will first need to connect to the MySQL server and specify which database in the MySQL server to operate on.

The mysql_connect() and mysql_select_db() functions are provided for this purpose. In order to connect to the MySQL server, the server name/address; a username; and a valid password is required. Once a connection is successful, the database needs to be specified.

The following 2 code excerpts illustrate how to perform the server connection and database selection:

@mysql_connect("[servername]", "[username]", "[password]") or die("Cannot connect to DB!");

@mysql_select_db("[databasename]") or die("Cannot select DB!");

The @ operator is used to suppress any error messages that mysql_connect() and mysql_select_db() functions may produce if an error occurred. The die() function is used to end the script execution and display a custom error message.

Executing SQL Statements against a MySQL database

Once the connection and database selection is successfully performed, the PHP script can now proceed to operate on the database using standard SQL statements. The mysql_query() function is used for executing standard SQL statements against the database. In the following example, the PHP script queries a table called tbl_login in the previously selected database to determine if a username/password pair provided by the user is valid.

Assumption:

The tbl_login table has 3 columns named login, password, last_logged_in. The last_logged_in column stores the time that the user last logged into the system.

// The $username and $passwd variable should rightly be set by the login form

// through the POST method. For the purpose of this example, were manually coding it.

$username = john;

$passwd = mypassword;

// We generate a SELECT SQL statement for execution.

$sql="SELECT * FROM tbl_login WHERE login = '".$username."' AND password = '".$passwd."'";

// Execute the SQL statement against the currently selected database.

// The results will be stored in the $r variable.

$r = mysql_query($sql);

// After the mysql_query() command executes, the $r variable is examined to

// determine of the mysql_query() was successfully executed.

if(!$r) {

$err=mysql_error();

print $err;

exit();

}

// If everything went well, check if the query returned a result i.e. if the username/password

// pair was found in the database. The mysql_affected_rows() function is used for this purpose.

// mysql_affected_rows() will return the number of rows in the database table that was affected

// by the last query

if(mysql_affected_rows()==0){

print "Username/password pair is invalid. Please try again.";

}

else {

// If successful, read out the last logged in time into a $last variable for display to the user

$row=mysql_fetch_array($r);

$last=$row["last_logged_in"];

print Login successful. You last logged in at .$last..;

}

The above example demonstrated how a SELECT SQL statement is executed against the selected database. The same method is used to execute other SQL statements (e.g. UPDATE, INSERT, DELETE, etc.) against the database using the mysql_query() and mysql_affected_rows() functions.

About The Author

This PHP scripting article is written by John L. John L is the Webmaster of The Ultimate BMW Blog! (http://www.bimmercenter.com).

The Ultimate BMW Blog!

daboss@bimmercenter.com



Top Bluetooth Wireless Headsets

Bluetooth headsets make up one of the fastest wireless markets here in the US and around the world. Headsets with Bluetooth wireless technology are capable of working with a variety of other Bluetooth enabled devices such as cell phones, PDAs, and digital music devices (like the iPod). Unlike conventional headsets, Bluetooth headsets do not require wires of any sort, but rather receive information from your portable device through 2.4GHz radio waves. The range of communication for most headsets is somewhere around 10 feet, which is usually plenty long.

Not surprisingly, there are a wide variety of Bluetooth headsets out there, and it really comes down to tastes in styles and preferred features as to which one is right for you. You'll want to make sure, for instance, that your Bluetooth device - whether it be an iPod, laptop, or PDA - will work with your chosen headphones. Here we list below some of the most popular Bluetooth headsets and their relevent features.

Logitech Mobile Bluetooth Headset

Logitech's Bluetooth headset is a real competitor in the market. It is a solid product with a dependable brand name, fully capable of providing sound connection between your cell phone and the headset. The device is entirely compatible with most major Bluetooth phones, but you may have to look into its compatibility with other devices. Like most headsets, the device can clip easily to either ear. It comes with an adjustable, swing-out boom that includes a noise-blocking microphone. The battery unit is rechargeable and is capable of giving you about 7 hours of talk time.

Motorola Bluetooth Headsets

Motorola currently has two stylish Bluetooth headsets on the market: the HS810 and HS820, and one soon to be released: the HS850. The HS810 and HS820 are very similar in style and shape.

Both devices are, of course, Bluetooth enabled and can thereby communicate with Bluetooth 1.1 compliant devices, including handsets, PDAs and computers. The device is compatible with the Motorola V600 and V710 phones. The HS810 and HS820 both weigh about 20 grams, and the HS820 has a slightly longer talk time range of 6 hours, compared with the HS810's 5 hours max. They both can run on standby for 100 hours. The HS820 has the ability to communicate with your phone up to 33 feet away, and is equipped with a couple nice features: conference call and voice dialing. The HS810 sells for $99.00 and the HS820 for $79.00.

Information concerning the newest headset by Motorola, the HS850, has just recently been released. Those lucky enough to have tested and reviewed this device have, so far, given it high marks. Like it predecessors, the HS850 has a simple yet attractive design. The main casing is black, with silver around the control area (image below). One of the more innovative features of this device is the flip-on connection system that enables the headset to connect with your phone as soon as you flip it open.

Jabra FreeSpeak Bluetooth Headsets

Jabra, a leading provider of hands-free communication devices is optimistic about its newest headset the Jabra FreeSpeak FS258 released recently in Malaysia. Weighing only 23 grams, the FS258 is the lightest behind-the-ear device produced by Jabra. The company is encouraged by a new trend in the US towards banning the use of cell phones while driving is some states, such as New Jersey.

Bradley James is a senior editor at SciNet.cc, a website containing many helpful consumer electronics review articles. For more information on Bluetooth wireless technology, please visit our Bluetooth headset webpage.



Homosexuality, Homophobia And The Christian Right

Focus on the Family says that they do not promote hate but yet when I was there (at Focus on the Family), I watched a video saying that homosexuals were out to attack families and that homosexuals had an agenda to ruin them.

This to me is funny and very sad. Do you really think we are hatched or something? We also are human beings and have families. It is very sad for me, especially my family that the Christian Right tries to pass laws that do not allow gays any basic rights. Two examples would be basic domestic partner benefits and hospital visitation rights. Additionally, the Christian Right believes it to be okay to fire someone for having a homosexual orientation. This to me is crazy. How is that equality? The problem is that you are unable to look at a homosexual and see the person/individual. You refuse to see good, just a pathological sexual deviant.

The Christian right chooses to demonize homosexuality as if it is all bad. Sexual orientation is simply that, it is sexual orientation. It is whom we are attracted to sexually and emotionally. We see heterosexuals who abuse their sexual orientation with sex/drug/alcohol addictions and other problems just as homosexuals. But yet you do not pathologize heterosexuality. Additionally, it is preached that homosexuality is a sickness and these people are the cause of AIDS. In fact, most AIDS cases are from heterosexual relations. Also, AIDS is a worldwide problem that affects people from all over the world. The Christian Right argues we need to focus more on medical issues like heart disease than AIDS. I do not agree because most heart disease cases are found in the US and Europe mainly because of poor diet and unhealthy lifestyle choices. Examples include but are not limited to not getting enough exercise, smoking, high saturated fats, etc.

It is important to note that homosexuals can have healthy loving relationships as well. But you will not look at that. Instead, you turn to a scripture on Sodom and Gomorrah. I have read that scripture many times and it does not speak about homosexuality. That scripture is clearly about rape. It is about men that want to have sex with other men against their will. The scripture also does not lie about how women were viewed in the older Hebrew society, and how women at that time lived in a clearly sexist culture. Hence, Lot attempts to give these men his daughters for them to have sex. I never hear anyone ever say how insane that is. Let's cut to the chase here and say that rape is unacceptable whether it is homosexual or heterosexual. Again, the problem is that Christian Fundamentalists lump us all in one category. We are pathologized. The sad thing is that there is no awareness of that. Thus, this is why homosexuals are a marginalized population and continue to be marginalized.

I am an openly gay man. My sexual orientation is big part of my life but not everything. I have a partner, a family, a relationship with my parents, and relationship with my sister, brother in law and my nieces and nephews. I am close to all of them. However, I still have to worry about being called faggot on the streets and have had employers preconceive ideas (negative) about who I am because of my sexual orientation. Additionally, I have had my life threatened numerous times simply because someone thought I was gay. You see, my mother, who is Catholic woman, told me that she does not worry about me catching AIDS but rather she worries about me being gay bashed and murdered.

This is her biggest worry. So, where does this hatred come from? I believe that it comes from churches and authorities in higher institutions such as the government. For example, the military and their don't ask don't tell policy. Clearly, we know what this says about gays. This sets up a good/bad tier system regarding sexual orientation. Again, gay is bad. So I wonder, what is the evidence of that? According to the American Psychological Association, the American Psychiatric Association and the American Counseling Association, there is no supporting evidence that suggests a significant difference between how homosexuals and heterosexuals deal with life and their problems. Fundamentalists, such as Focus on the Family take a few examples and then lump gays into one category, which says we are ill and sick.

The Christian Right ignores or fails to recognize that heterosexuals do and have behaved in similar ways that they say homosexuals do. When a gay person does something wrong, Fundamentalists are quick to point out that we all do it, further perpetuating false, untrue beliefs about all homosexuals. This clearly makes it more difficult to exist in the world. Despite my loving family and the loving support I have from them, I still have to live in this world. I must work and I must go to the grocery stores and malls. I have been almost gay bashed three times after leaving a gay bar with friends at different times and different places in my life in this so called free country. So you really do not understand the power that you have as preachers or pastors? The unfortunate piece is that when you preach that homosexuality is evil, others take those views and believe it. They believe they should and have the authority to enforce them. They may be verbal slurs or even result in violence. I know you say you don't promote this but it happens and these people (your fellow Fundamentalist Christians) use the bible and religion to perpetuate hate by engaging in this verbal and physical violence.

That is how oppression is perpetuated and this is why gays are still a marginalized population. Christians do not have to worry about walking down the street with their husband or wife and get slurred or harassed based on being who they are. Men and women can hold hands together or kiss in public. I do not have that right; otherwise I could get gay bashed. It has happened to my partner and me where we have been threatened when walking home from a grocery store. So no I do not believe that heterosexuals or Christians are a minority. I do not think you clearly understand what it means to be oppressed or be lumped into a category. Gay people have lost their lives because of their sexual orientation and that is THE REALITY.

I believe what you might have been referring to is that you are experiencing an out lash from a group of people tired of being oppressed. I am sorry you have to deal with that but that is what happens when a wounded dog gets backed into a corner. We have seen that happen in other oppressed groups in the United States. Gays have been wounded by an oppressive society and thus we fight for our BASIC RIGHTS. We fight for ourselves, our partners and our families, so that we can live the life that heterosexuals already live. I have hope one day that my partner and I could hold hands and express affection in public.

I don't because it worries him. He does not know how to defend himself and so I do not want him to be harmed. I love him too much for that to happen. However, this does anger me because in my family, I was taught to express my emotions and affections. I learned to love in my family and was taught that you told the ones you care about how you feel. I also learned to express my affections in order to make my future partner feel special. I know you probably won't validate what I have said but it is true. We are human beings with emotions and feelings.

In fact, we are all more the same than different. Maybe one day you will really look at what it means to be Christian, to be Christ like. And as far as I know, Christ understood people, loved them, respected them and validated them. I believe these are the values we need to teach people. We need to look at people individually. We should not judge groups of people and lump them into categories. Thus, in my life and the way I live, I want to look at the individuals and not judge groups of people. I realized that if I lumped people into groups, I would not be able to like anyone on this planet. And in my opinion, there is too much beauty and love in certain people that I don't want to miss out. This includes everyone from all groups!

Barry Aneda is a National Certified Counselor and a Licensed Associate Counselor working with our GLBTQ community in the field of Addictions and HIV/AIDS.

For more information you can reach him at http://www.barryaneda.com To visit his virtual office, simply click the link titled Visit My Virtual Office.



Make Money In A World of Endless Opportunity

Giants crush you. Even in fairy tales it's rare to find a nurturing giant even lady giants are tough critters. And there are lots of giants on the web; all the world's biggest offline companies plus the web's home-grown efforts - Google, Amazon and the like.

So how can you, sitting in your fabled pajamas at the kitchen table make money against that lot? Well, until recently there was no way to really explain what everyone was telling you based on instinct, self-interest or outright ignorance: there is room for everyone on the web.

It's called the long tail: the economics of abundance' and its guru is the editor of Wired Magazine Chris Anderson. Now don't let that put you off, this is fascinating stuff! The summary is simple: regular offline business is ruled by scarcity, digital business simply isn't!

Take a record store. They have so many feet of shelves and each CD takes up say half an inch. Result, the store can only carry so many CDs. So what do they do? They carry the ones that sell the most the hits.'

Now take iTunes: there is literally no limit to the inventory iTunes can carry. It sits in digital form and could be every song in every version ever recorded! The same is true of books: which is why Google is trying to snaffle them all first, and Apple is driving into video.

So what has this to do with you? Well two things: first the big web marketers have discovered that if you offer everything, "everything sells something!" Hence the term long tail.

Imagine the profile of a mouse standing on her back legs nose pointing in the air! The body of the mouse is the hits' with the biggest hit being the nose. The tail of the mouse (infinitely long) is the sales of everything else. The regular record store holds inventory corresponding to the body of the mouse. But, if you hold the inventory for free and it costs nothing to deliver it, then any sale out of the tail is pure profit! Wow! That's the economics of abundance: and it's only right now being understood.

But, I hear you object, that's records, books, and videos. True, but the same applies to everything where the restrictions of scarcity are removed.

What's eBay but a long tail of gazillions of real things? What's Amazon, the long tail of books and anything else they can get their hands on? So it continues the used book business after languishing for decades is booming after the dispersed and happenstance inventories held by individual stores were linked together into a single online database. The books are still in the stores, but the sales are global!

Now if you are an Amazon, or a Salesforce.com in software, or any of the other aggregators' of the long tail', you have five problems:

1. You need to put together the technology to hold the inventory and disperse it expensive and technically finnicky, but straightforward

2. You need to create the tools that customers can use to search the long tail which is VERY long. Search engines, recommendations, reviews all kinds of tools are emerging to provide filters at no cost to the company once they are in place.

3. You need to get your hands on the longest tail you can. Easier now Apple has broken through with the record industry, but really difficult if you want to have a long tail of TV shows because of the problem of tracing down the music rights. Google may be in a battle, but the stakes in the ancient book long tail are huge hence its determination to scan everything ever published.

4. You need to capture the emerging long tail. These are the products and creative offerings that have not yet been conceived. You do this by giving away the tools of creation. Give away (virtually) the software to create new music and provide a guaranteed market.

5. You need to meet the sales needs of the provider whether they are trying to make a go of it commercially or doing it for reasons of personal satisfaction. Put your book on Amazon and you can go in and tweak the marketing and this is just the beginning.

So what are the implications for web home-based businesses?

It means first you can expect sales no matter if you are 1st or 5,000th on the tail.

It means you can find a place on the web through an aggregator for what ever you produce.

It means that multiple channels of distribution are opening that can have different roles in your mix. Let's take a concrete example, that new book you just wrote.

* Well you could sell it yourself in electronic form, or

* Convert it into a physical book at Lulu (a 'tail' of self-pubished books) and end up with electronic and soft/hard copy versions yielding a higher net return.

* Lulu will submit it to Ingrams the book wholesalers and so it will find its way to the long tails run by Amazon, Barnes & Noble and the rest for a different, lower return but a much higher exposure and access to the recommendations system.

* You could sell it through Clickbank a long tail of Affiliates and make 50% margin.

* Finally, you can sell or liquidate it through eBay!

If you have something to offer, a tail is emerging that you can join. And most important, it's in everyone's interest to keep the tail growing. On the web we have invented the nurturing giant'. To me that spells perpetual opportunity!

And that's no fairy story!

Michael Kay is Research Director of HBB Research a business school based research program looking at web home-based business. He is the lead author of HBB Research's recent Report: The Gold Rush. To For more on The Gold Rush and to get your free subscription to HBB Insights, the ideas newsletter of HBB Research, go to http://www.hbbresearch.com/.