Top Web Hosting Reviews
Top Web Hosting Provider of The Month:
Top Web Hosting
Visit Bluehost.com | Read Bluehost Review

>> Web Hosting Geeks // Web Hosting Articles // Web Development  


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!

    daboss@bimmercenter.com


    MORE RESOURCES:

    Web Development at HiddenBrains Brings Single Platform for Comprehensive Web ...
    Online PR News (press release)
    Web is the source of global exposure for business companies as well as source of IT services for economic web development. The search for appropriate and ...
    Web Development Company offering Dedicated PHP Developers at USD 1500I-Newswire.com (press release)
    PHP Web development has become the Source of HiddenBrains GoodwillBigNews.biz (press release)

    all 5 news articles »


    Hudson Horizons Ranked as the Best Web Development Agency for March 2010 by ...
    Online PR News (press release)
    bestwebdesignagencies.com, the independent authority on the best web development, has ranked the best web development agencies for March 2010. ...

    and more »


    Bullseye Media Recognized as the Best Web Development Firm in the United ...
    PR Web (press release)
    The independent authority on search vendors, uk.topseos.com, released the March 2010 rankings of the best web development firms in the UK. ...
    Bullseye Media Ranked Number 1 SEO Web Development Company in the UKPR Web (press release)
    Bullseye Media Recognised As Top UK Link Building CompanyPR Web (press release)

    all 5 news articles »


    Contus Support - Preferred Offshore Web Development Company in India
    I-Newswire.com (press release)
    Contus Support Interactive – http://www.contussupport.com, a complete web solutions company helps to provide all kinds of web development solutions across ...



    The Time is Now for Mobile Web Development
    HTML Goodies
    WebKit, a layout engine used by many mobile devices and web browsers, allows web developers to create mobile websites with CMS functionality. ...

    and more »


    Ann Arbor's Logic Solutions Merges With Web Development Firm
    WWJ
    Ann Arbor-based Logic Solutions Inc. has merged with the Ann Arbor Web site development firm Arachne Web Technologies. Logic COO Bruce Richardson said the ...



    Emmet County hires new communications, Web director
    Petoskey News-Review
    To reach her with Web development or other communications related ideas, contact call (231) 348-1704, or e-mail bpiehl@emmetcounty.org.



    The Best Web Development Companies for March 2010 Ranked by topseos.com.au
    Online PR News (press release)
    Thousands of vendors were put through a stringent evaluation process in order to find the best web development companies. Online PR News – 17-March-2010 ...

    and more »


    Why I will be voting 'yes'
    The Coloradoan
    Before I was a public servant, I was a small-business owner, keeping the books in the Web development firm my husband and I started together. ...

    and more »


    Web Development Firm Bayshore Solutions Wins Gold ADDY® for Their Work with ...
    PR Web (press release)
    Winning a Gold ADDY® Award for web development and design work on Grow4Students.org, a student banking website for Grow Financial Credit Union, ...

    and more »

    Google News





  •  
     
     

    © 2004 - 2008 "Web Hosting Geeks" | Web Hosting Reviews | Customer Reviews | RealMetrics Reviews | Hosting Articles | Directory | Partners | Contacts
    Over 7000 articles: web hosting, web development, domain names, ecommerce, web design, site promotion, ppc advertising, seo, site promotion and many others.
    Web hosting reviews, ratings and awards are not based on any incentives or commissions. Names and trademarks are the properties of their respective owners.
    A direct link to Web Hosting Geeks (http://webhostinggeeks.com) must be provided in order to use any of the above information. Contact us for more info.

    Partners: Hosts by speed, Cheap Website Hosting, Free Website Hosting, Cheap Web Hosting, Top 10 Web Hosts, Top 10 Web Hosting Deals, Best Website Hosting, Free Web Hosting, Free Web Hosting, Dedicated Server Hosting, Adult Web Hosting, Web Hosting Discussions, Dedicated Server Reviews, Best Web Hosting, Web Hosting Discounts, HostProfessor.com, rsuog, halyava, PHP Website Hosting Services, Web Hosting Reviews, Hosting Uptime, Best Web Hosting Reviews, Cheap Webhosting, Web Hosting, Flash Templates, CMS Templates, Web Hosting Reviews, Website Hosting Reviews, Web Hosting Providers, Best Web Hosting, Top Web Hosting, RSUOG Web Hosting