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 customer's personal login details; and the customer's 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:

  • 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.

  • The inability to efficiently control access by users to the data

  • 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:

  • Connect to a MySQL database

  • 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, we're 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!

    http://www.bimmercenter.com

    same day cleaning service Bannockburn ..
    In The News:

    A new green energy system is set to change how we capture clean power, and it all starts with the ocean. French startup Seaturns has designed technology that taps into the natural motion of the sea.
    Cybersecurity researchers are warning that hackers have started exploiting flaws in chatbots to carry out AI phishing attacks.
    Google has just made it easier than ever to regain control of your inbox with Gmail's new Manage Subscriptions tool.
    Despite the benefits, residential power saver programs come with several potential drawbacks and concerns that have been raised by both customers and experts.
    The Blackdot AI tattoo machine is quiet. It's steady. And according to early users, it hurts a lot less.
    Attackers have started to exploit the very signals that users assume will keep them safe when it comes to add-ons to improve productivity or entertainment.
    Located on Cerro Pachón in Chile, the world's most powerful digital camera is set to transform how we see the universe.
    The innovative DQ Tower stands 28 feet tall with 420 square feet of living space, featuring floor-to-ceiling windows and premium amenities in a prefabricated design.
    A new mmWave imaging system allows warehouse robots to scan and create 3D models of objects inside sealed containers, potentially revolutionizing shipping processes.
    Family fraud endangers seniors when relatives exploit their trust, but removing personal data online and monitoring identity can prevent financial harm to aging parents.
    A study analyzing 500,000 customer service interactions shows chatbots struggle with complex issues while human agents excel at matching customer communication styles.
    Aigen's Element robot uses solar power and AI to provide farmers with a sustainable alternative to herbicides, working efficiently in cotton and soy fields.
    Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
    Cybercriminals accessed Medicare data of more than 100,000 Americans by creating fraudulent accounts, prompting CMS to deactivate accounts and issue new Medicare cards.
    China's battery swap technology from CATL lets electric vehicle owners exchange batteries in under two minutes, with plans to expand to 1,000 stations across 31 Chinese cities by 2025.
    Analysts at Silent Push have uncovered a widespread scam that uses counterfeit retail websites to steal the credit card information of online shoppers.
    Chrome users need to update their browsers immediately as Google addresses a critical vulnerability that hackers are actively exploiting. Additional security measures are recommended.
    A study found teens glance at phones for dangerous two-second intervals while driving, using devices primarily for entertainment, texting and navigation despite crash risks.
    Security researchers uncovered a flaw in Windows 11 that allows attackers to disable Secure Boot using Microsoft-signed tools, requiring manual updates to protect against bootkits.
    Carnegie Mellon's noninvasive brain technology allows users to move robotic fingers by thinking about the motion, offering new possibilities for people with motor impairments.
    Multi-factor authentication (MFA) adds an extra layer of protection to your accounts. Instead of relying only on a password, MFA requires you to verify your identity using two or more methods.
    Scientists from Duke, Harvard, and the University of Otago have unveiled a game-changing tool called DunedinPACNI. It uses a single AI brain scan to reveal how fast a person is biologically aging.
    A disturbing wave of fake agent phone scams is sweeping across the United States, catching people off guard and draining their savings.
    Emojis aren't just playful add-ons; they're powerful tools for building stronger connections in our increasingly digital world.
  • HTML Editors 101 - Smaller Is Better

    SiteSpinnerSiteSpinner is a user-friendly web site development tool that includes... Read More

    Setting Up Your First Website

    Q. Hey, Cathy: I'm just setting up a website. What... Read More

    You Don?t Have to be Amazon.com to Achieve 12% Conversion Rates!

    That's right. According to a recent study by Nielsen/NetRatings, Amazon.com... Read More

    Benefits Of Making Your Website Accessible To Disabled Users ? Part 2: The Business Case

    The Disability Discrimination Act states that service providers must not... Read More

    The 2 Most Common Web Site Mistakes

    When we review the sites of potential clients, there are... Read More

    Free Webmaster Tools - 7 Things Every Webmaster Needs in Their Toolbox

    Webmaster tools are vital to becoming both efficient and effective... Read More

    Why A Simple Counter is Never Enough for Your Website

    A simple website stats counter is not enough if you... Read More

    What Hosting Companies Dont Tell You, Could Hurt You?

    Did you know that hosting companies overcrowd their servers despite... Read More

    Websites for Writers ? Why You Need One and How to Get Started Today

    It may seem like the publishing industry's equivalent of Beanie... Read More

    Entangled in the World Wide Web

    I am just a learner who likes to delve in... Read More

    Allocating Your Web Site?s Budget Properly

    I had a client say something to me the other... Read More

    The Number 1 Reason Most Websites Fail

    Failure, just like success, is measured differently by each and... Read More

    How Your Own Website Helps Your Small Business Grow

    What do you mean, you don't have a website for... Read More

    Effective Webdesign

    D.zigns dzignerwebs The Basics Before starting on... Read More

    The Importance of Website Stats to You

    One of the best tools you have as a webmaster... Read More

    Functions and Subroutines in ASP

    Functions and Subroutines in ASP If you read... Read More

    Creating a Sticky Web Site

    When used to describe a web site, the term "sticky"... Read More

    Free Websites & Why You Should Avoid Them

    It amazes me how many people try to build serious... Read More

    Art, Artists and the Web: Part 4--What to Do After a Website is Designed

    What to do if you are an artist after you... Read More

    Web Measurement: What You Don?t Know Would Make A Great Book

    "What's in it for me?" you ask. "Why should I... Read More

    Conceptualize, Build and Publish a Web site

    Conceptualize, Build and Publish a Web site - What's required... Read More

    Why Local Service Companies Should Have a Website

    The Internet is being used by local service business to... Read More

    How Web Templates Are Helping Online Businesses to MultiplyTheir Income

    Web templates by nature are created to aid and ease... Read More

    Develop a Solid Website Presence

    Starting an internet business can be confusing to non-veterans. The... Read More

    How To Get Profits From Your 404 Page Not Found File

    "'Page Not Found' on this Server. Check the URL and... Read More

    housekeepers near Deerfield ..