Topic outline

  • Introduction

    MySql is probably the worlds most popular database engine.

    Unlike MS Access it does not run as a stand-alone application.   It runs as a background service on a computer (typically called ‘a server’) and you connect to it using a username and password.  Once you have connected to the MySql server you can query it using SQL or Structured Query Language.  The server will respond with the results of your query.

  • Connecting to a MySQL Database

    Connecting to the MySql database via PHP is done through the CONNECT functions. There are two connect functions to chose from:

    $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
    $link = mysql_pconnect('localhost', 'mysql_user', 'mysql_password');

    The pconnect function will create a persistent connection to the database which will not die. The formerconnect function will not. If subsequent connection attempts are made to connect then the connect link will be refreshed and additional ones are not created. It is possible to flood the MySql server when usingpconnect and therefore its use is discouraged.

    Once you have connected to the MySql server you need to select the database you wish to use. This is done using the mysql_select_db function

    mysql_select_db('database_name', $link);

    Obviously you should program in control measures when connecting to the database to protect your system in case the connect attempt fails . In which case the or die syntax is very helpful:

    $link = mysql_connect( 'host.name', 'user', 'password') 
      or die('Could not connect to server.' );
    $db = mysql_select_db('database_name', $link) 
      or die('Could not select database.');

     

  • Feedback

    Getting helpful feedback from MySQL when it errors is possible if you use the following:

    mysql_query($sql) or die('Some useful message:<br />' . mysql_error() );
  • Deleting Data

    If you need to delete a row you can use the DELETE command with a WHERE clause dictating which ones:

    DELETE FROM `tbl_name`WHERE `fieldx` = "X";

    Example:

    DELETE FROM `criminals` WHERE `crime` = "Arson";

    Further Information and examples here

  • Indexes

    Indexes are used to speed up searching on columns within tables. They can increase performance if used correctly but can also have costs as the index record must be updated with every change. Primary keys will become indexes by default.

  • Inserting Data

    Inserting rows into MySql can be done in a couple of ways. You can use the INSERT…VALUES and INSERT…SET commands.

    The first option INSERT…VALUES syntax is:

    INSERT INTO `tbl_name` VALUES ('fieldvalue1', ... , 'fieldvalueN');

    Example:

    INSERT INTO `criminals` VALUES (NULL, 'Andrews', 'Donald', 'M', '24', 'Arson', '87', '182', '11', 'A+', 'BS3 5TY', 'X324 TYR', 'Ford', 'Focus', 'Blue' );

    The second option INSERT…SET syntax alternative requires that you specify each field name with its counterpart in the same format as update queries.

    `surname` = 'Smiths', 
    `firstname` = 'John'

    If you are inserting new values in every field for a table then the first option is the most simple. You can always design your system such that it will accept NULL values. If however you only want to insert values into particular fields within a table you could use the second option.

    What ID was that field given?

    Often after inserting a row you want to know what value that row was given. MySql will return the last insert row with the following php command

    mysql_insert_id();

    Further Information on INSERT

  • Creating Databases and Tables

    You can run MySql from a command line and set up everything up from there. However this is beyond what you would be expected to do at A-Level and therefore I recommend installing PHPMyAdmin and using its interface. You will however need to make some decisions regarding data types.

  • Selecting Data

    To grab a bunch of data from an SQL database you need to write a SELECT query. The basic query looks like:

    SELECT * FROM `table_name`;

    But to run it via PHP it needs to be placed within a string and executed.

    $sql = "SELECT * FROM `criminals`;";
    $results = mysql_query($sql) or die('Could not query the database.');

    However often you will need to specify some sort of criteria or WHERE clause that restricts the data returned:

    SELECT * FROM `table_name` WHERE `fieldname` = 'some criteria';

    WHERE clauses can become very complex and use terms such as AND, OR and LIKE:

    SELECT * FROM `table_name` WHERE `fieldname` = 'some criteria' AND `another fieldname` = 'some criteria more';

    LIKE allows you to look for wildcarded values:

    SELECT * FROM `table_name` WHERE `fieldname` LIKE 'some criteria';

    Further Information and examples.

    Ordering and Limiting

    You can tell MySql to return information in a particular order using the ORDER or LIMIT instructions. More information on Ordering

    JOINS and Multiple Table Selects

    SELECT can be used across multiple tables but depending on the relationship between the data you may have to use the more complex JOIN method. More information on JOINS

    Accessing results from a SELECT query

    Once you have constructed your SQL query string and stored it in an PHP variable

    $sql = "SELECT * FROM `criminals`;"

    you will need to execute it.

    Executing sql queries is done by calling

    $result = mysql_query($sql);

    From the result you can access each of the returned rows through

    $row = mysql_fetch_row($result);
    $row = mysql_fetch_array($result);

    Both functions will return an array consisting of values from the row called.

    Each element in the array can then be reference using its associated location or field name e.g $row[0]; or$row['crime'];.

    More information can be found here

    HOW MANY ROWS HAVE BEEN RETURNED?

    If you need to know how many rows have been returned by your SELECT statement then you can call the following which will return the value as an integer.

    mysql_num_rows($results)

    IF YOU WANT TO ACCESS ALL THE ROWS RETURNED IN A RESULT

    If you want to loop through all the rows then use the PHP while loop

    while($row = mysql_fetch_row($result) { //Process Row }

  • Relationships

    Dealing with relationships in MySql is not as straightforward as either MS Access or as you would have hoped for.

    Creating simple primary keys isn’t too difficult

    CREATE TABLE `student` (
      contact_id INT(10), 
      name VARCHAR(40), 
      birthdate DATE, 
      PRIMARY KEY (contact_id)
    );

    However foreign keys are more complex and require the following code in the table creation code:

    FOREIGN KEY (foreign_id) REFERENCES foreign_table (foreign_id)

    This will ensure that you can only add foreign_ids when they exist in the foreign table.

    A full discussion on this topic exists here

    Good Explanation of Many2Many Relationships

  • Updating Records

    For updating fields within rows you can use the UPDATE command:

    UPDATE `tbl_name` SET `field1' = "fieldvalue1", ... WHERE `fieldx` = "X";

    Example

    UPDATE `criminals` SET 
      `forename` = "Mickey", 
      `surname` = "Mouse" 
    WHERE `id` = 654;

    There is an alternative which uses VALUES. The format is:

    UPDATE `tbl_name` SET `field1`, `field2` VALUES ('value1', 'value2') ....

    Further Information and examples here

  • Topic 10