Login or Register Now   Email:  Password:   

Introduction to PHP and MySQL

How they work together.

By Kevin Waterson <kevin@phpro.org>

Contents

  1. What is this tutorial?
  2. Getting started.
  3. Connecting to MySQL
  4. Creating a database
  5. Creating a MySQL user
  6. Creating a Table
  7. INSERT data into MySQL
  8. INSERT multiple records
  9. SELECTING data
  10. DELETING data
  11. UPDATING Data in MySQL
  12. LIMIT data selections
  13. Configuration Options
  14. Formatting Dates
  15. Load a CSV File
  16. Preventing SQL Injection
  17. Useful Tips

What is this tutorial?

This tutorial is aimed at those new to PHP and MySQL. The object of this tutorials is to show by way of example how to use php to CREATE a database, how to CREATE a table, how to INSERT data into a database, and how to SELECT that data and display it on a web page.

This tutorial does not cover the editting of data or the use of forms when sending data to a mysql database. These topics are covered in the Secure PHP MySQL tutorial. This tutorial will grow in size and complexity as time permits. Lets begin with a brief description of what MySQL and PHP are.

MySQL is a RDBMS. That is a Relational Database Management System. It uses a language called SQL (Structured Query Language) to add, access and process data within a database.

PHP is a scripting language that has revolutionised the way we serve information. Its powerful, yet simple C like syntax has made it a favorite of those just beginning in web technologies and those with strong programming backgrounds. The beauty of these two technologies is how well they come together in making dynamic information available over the net.


Getting Started.
This tutorial requires you to have a basic level of PHP and SQL. It also requires you to have these installed on your machine. It is beyond the scope of this document to detail the installation of PHP or MySQL and if you need help with these we suggest you read the appropriate installation instructions on php.net and mysql.com. PHP comes with three levels of interfacing with MySQL. These three extensions are

  1. mysql
  2. mysqli
  3. PDO

The first is the standard set of MySQL functions. The second, mysqli, is Mysql Improved. This extension contains a feature rich interface to later version of MySQL and has a gnarly OO interface. Thirdly, the ubiquitous PDO (Php Data Object). The PDO extension provides a standard interface for accessing many databases. It is not as feature rich as mysqli but for most uses, it provides a standard method of interacting with all databases.Detailed installation intructions can be found in the very fine PHP manual. During this tutorial we will show how various tasks are accomplished using all three methods.

Connecting to MySQL.

Before we can do anything with MySQL we need to be able to connect to the server. Here we will demonstrate 3 ways of doing this with PHP mysql, mysqli and PDO. First with the standard mysql connection.

Connecting with mysql.


<?php

/*** mysql hostname ***/
$hostname 'localhost';

/*** mysql username ***/
$username 'username';

/*** mysql password ***/
$password 'password';

/*** connect to the database ***/
$link = @mysql_connect($hostname$username$password);

/*** check if the link is a valid resource ***/
if(is_resource($link))
    {
    
/*** if we are successful ***/
    
echo 'Connected successfully';

    
/*** close the connection ***/
    
mysql_close($link);
    }
else
    {
    
/*** if we fail to connect ***/
    
echo 'Unable to connect';
    }
?>

Before we move on with the other extensions, lets look briefly at what has happened above. We have begun by setting some variables for our database, these are the hostname, username, and password. The next line of code shows the use of mysql_connect() function to connect to the MySQL server. Lets look at this line further.

$link = @mysql_connect($hostname, $username, $password);

We have created a mysql link resource variable called $link. We see also here the use of the @ symbol to suppress and errors that may arise from a failure to connect, more on this later..., After we use mysql_connect() we check with the is_resource() function that the link variable is indeed a valid resource, and if so, we can continue with our code, else, an error is printed saying Unable to connect. If the connection is valid, then a message is printed to say so, and the database link is closed with the mysql_close() function. The database connection should cease at the end of the script, but with longer running scripts this may be a waste of valuable resources, so we free up some room with mysql_close(). Now, lets see the same thing with mysqli..

Connecting with mysqli.

This could simply be done in the same manner as mysql_connect(), but mysqli offers us an Object Oriented (OO) interface to MySQL so it would be futile to do things "the old way". Lets see how we go.


<?php

/*** mysql hostname ***/
$hostname 'localhost';

/*** mysql username ***/
$username 'username';

/*** mysql password ***/
$password 'password';

/*** create a new mysqli object ***/
$mysqli = @new mysqli($hostname$username$password);

/* check connection */ 
if(!mysqli_connect_errno())
    {
    
/*** if we are successful ***/
    
echo 'Connected Successfully';

    
/*** close connection ***/
    
$mysqli->close();
    }
else
    {
    
/*** if we are unable to connect ***/
    
echo 'Unable to connect';
    exit();
    }
?>

Here we see the creation of a new mysqli object which passes the hostname, username, and password to the constructor which makes the connection for us. We can then use this new object for other functionality that we will soon use. We have also suppressed error_reporting with the @ symbol once more, this is because a warning will be produced if the connection fails. We have also tested for an error condition (more on errors later) to see if the connection is valid, and if so, it tells us. Now, lets move onto PDO.

Connecting with PDO

PHP has spawned an amazingly neat idea to standardize database connections. This is PDO (Php Data Objects). A full Introduction to PDO is available and is well worth reading. Here we will use some of the concepts from this article to use with mysql. So, lets get connected


<?php

/*** mysql hostname ***/
$hostname 'localhost';

/*** mysql username ***/
$username 'root';

/*** mysql password ***/
$password 'rootpass';

try {
    
$dbh = new PDO("mysql:host=$hostname;dbname=mysql"$username$password);
    
/*** echo a message saying we have connected ***/
    
echo 'Connected to database'
    }
catch(
PDOException $e)
    {
    echo 
$e->getMessage();
    }
?>

In the above code, several variations have taken place. Like the other connections we have supplied a hostname, username, and password. PDO demands that we also have a valid database to connect to. If no database is specified an exception is thrown. In the example above we have used the default mysql database to connect to. The database named mysql contains the tables of users, databases and other vital information. YOU HAVE BEEN WARNED! We use the catch{ } block to catch any thrown exceptions from the try{ } block. Another variation is that we have used root as the username.
Is this a bad idea?
In most circumstances yes, however, here we wish to demonstrate some administrative tasks such as creating users and creating databases. Most MySQL servers, by default, will not allow this to be done by a user other than the root super user. In the following section we will be creating a database, so root access is required.

Creating a Database.

Now we have seen how to connect to a database server, it is just a small step to create a database. You will need to be a user with CREATE privileges to do this. Usually this will be the user root, so thats what we will be using here. Once again we will use the three different PHP mysql extenstions to do this, beginning with the mysql extenstion.

Create with mysql.


<?php

/*** mysql hostname ***/
$hostname 'localhost';

/*** mysql username ***/
$username 'root';

/*** mysql password ***/
$password 'rootpassword';

/*** connect to the database ***/
$link = @mysql_connect($hostname$username$password);

/*** check if the link is a valid resource ***/
if(is_resource($link))
    {
    
/*** if we are successful ***/
    
echo 'Connected successfully<br />';

    
/*** sql to create a database ***/
    
$sql 'CREATE DATABASE periodic_table';

    
/*** run the sql query ***/
    
if(mysql_query($sql$link))
        {
        echo 
'Database created successfully<br />';
        }
    else
        {
        echo 
'Unable to create database: <br />' $sql .'<br />' mysql_error();
        }
    
/*** close the connection ***/
    
mysql_close($link);
    }
else
    {
    
/*** if we fail to connect ***/
    
echo 'Unable to connect';
    }
?>

In the above code the we have used the function mysql_query() to run the SQL statement
CREATE DATABASE periodic_table
You may ask why we created the variable $sql when it would have been just as easy, and used less code to embed the sql query as an arguement for the mysql_query() function like this:


mysql_query("CREATE DATABASE periodic_table")

We created the variable $sql for possible debugging purposes. Should we encounter an error within our sql statement, the error checking will print a message, including the sql statement. Eg: should we run this script twice, we would see an error something like this..

Connected successfully
Unable to create database:
CREATE DATABASE periodic_table
Cannot create database periodic_table; database exists

Create with mysqli.

The mysqli connection provides a smooth object oriented approach for same functionality. Using the connection code from the earlier connect script we can simply use the created mysqli object to run queries.


<?php

/*** mysql hostname ***/
$hostname 'localhost';

/*** mysql username ***/
$username 'root';

/*** mysql password ***/
$password 'rootpassword';

/*** create a new mysqli object ***/
$mysqli = @new mysqli($hostname$username$password);

/* check connection */ 
if(!mysqli_connect_errno())
    {
    
/*** if we are successful ***/
    
echo 'Connected Successfully<br />';

    
/*** our sql statement ***/
    
$sql 'CREATE DATABASE periodic_table';

    if(
$mysqli->query($sql) === TRUE)
        {
        echo 
'Database created successfully<br />';
        }
    else
        {
        echo 
$sql.'<br />' $mysqli->error;
        }

    
/*** close connection ***/
    
$mysqli->close();
    }
else
    {
    
/*** if we are unable to connect ***/
    
echo 'Unable to connect';
    exit();
    }
?>

Should we run this code twice, we would again get an get an error like the following

Connected Successfully
CREATE DATABASE periodic_table
Cannotcreate database periodic_table; database exists

You can see from the message, as in the previous example, we have a message to tell us that we have connected successfully, then the SQL query used followed by a message from the database itself telling us the exact nature of the error.

Create with PDO

Not to be out-done in the Object Oriented approach, PDO makes the code base somewhat cleaner. Using the code from the initial connection we can use the provided DSN object for our query.


<?php

/*** mysql hostname ***/
$hostname 'localhost';

/*** mysql username ***/
$username 'root';

/*** mysql password ***/
$password 'rootpassword';

try {
    
$dbh = new PDO("mysql:host=$hostname;dbname=mysql"$username$password);
    
/*** echo a message saying we have connected ***/
    
echo 'Connected to database<br />';

    
/*** set the PDO error mode to exception ***/
    
$dbh->setAttribute(PDO::ATTR_ERRMODEPDO::ERRMODE_EXCEPTION);
    
    
/*** our sql statement ***/
    
$sql 'CREATE DATABASE periodic_table';

    
/*** we use PDO::exec because no results are returned ***/
    
$dbh->exec($sql);

    
/*** echo a message to say the database was created ***/
    
echo 'Database created successfully<br />';
    }
catch(
PDOException $e)
    {
    
/*** echo the sql statement and error message ***/
    
echo $sql '<br />' $e->getMessage();
    }
?>

As you see, PDO provides a nice exception class to handle any problems that may arise in our database queries. If an exception is thrown within the try{ } block, no further code within the try{ } block is executed and the flows directly to the first catch(){ } block. In the catch block above we echo the SQL statement and any error message that may be generated by the database.

This query is not one you will be running often but is needed in order to show how to create database tables. Below is the SQL statement needed to create the a table and fields within your newly created database.

Creating a MySQL user

Now a database has been created, a user other than the root user needs to be able to work with it. This means a MySQL user, not a system user, needs to be created and given the appropriate permissions to be able to work with data. We will create a user with all permissions on the periodic_table database. If you want real security, you can limit the permissions a user has to just SELECT, thus limitting possible injection attacks. The topic of PHP/MySQL security will be covered in another article. For now, we will GRANT ALL privileges to the new user, except GRANT. Once again we need to have root access to mysql to do this. The code itself should look very familiar if you have read the previous section as it is almost identical. The same principles and connections apply, the only thing that changes is the SQL statement itself.

Create a user with mysql.

As mentioned, this is identical to creating a database, the only change is the SQL statement, we have reproduced the code here for the benifit of familiarity.


<?php

/*** mysql hostname ***/
$hostname 'localhost';

/*** mysql username ***/
$username 'root';

/*** mysql password ***/
$password 'rootpassword';

/*** connect to the database ***/
$link = @mysql_connect($hostname$username$password);

/*** check if the link is a valid resource ***/
if(is_resource($link))
    {
    
/*** if we are successful ***/
    
echo 'Connected successfully<br />';

    
/*** sql to create a user ***/
    
$sql "GRANT ALL ON periodic_table.* TO username@localhost IDENTIFIED BY 'password'";

    
/*** run the sql query ***/
    
if(mysql_query($sql$link))
        {
        echo 
'New user created successfully<br />';
        }
    else
        {
        echo 
'Unable to create user: <br />' $sql .'<br />' mysql_error();
        }
    
/*** close the connection ***/
    
mysql_close($link);
    }
else
    {
    
/*** if we fail to connect ***/
    
echo 'Unable to connect';
    }
?>

Create a user with mysqli.

Here also there are no changes except for the SQL. All the code remains as it was to create a database.


<?php

/*** mysql hostname ***/
$hostname 'localhost';

/*** mysql username ***/
$username 'root';

/*** mysql password ***/
$password 'rootpassword';

/*** create a new mysqli object ***/
$mysqli = @new mysqli($hostname$username$password);

/* check connection */ 
if(!mysqli_connect_errno())
    {
    
/*** if we are successful ***/
    
echo 'Connected Successfully<br />';

    
/*** sql to create a user ***/
    
$sql "GRANT ALL ON periodic_table.* TO username@localhost IDENTIFIED BY 'password'";

    if(
$mysqli->query($sql) === TRUE)
        {
        echo 
'New user created successfully<br />';
        }
    else
        {
        echo 
$sql.'<br />' $mysqli->error;
        }

    
/*** close connection ***/
    
$mysqli->close();
    }
else
    {
    
/*** if we are unable to connect ***/
    
echo 'Unable to connect';
    exit();
    }
?>

Create a user with PDO

And you guessed it, no changes here either from the CREATE DATABASE example above. Everything remains the same except for the SQL statement itself, the new user is created, and if there is a problem an exception is thrown.


<?php

/*** mysql hostname ***/
$hostname 'localhost';

/*** mysql username ***/
$username 'root';

/*** mysql password ***/
$password 'rootpassword';

try {
    
$dbh = new PDO("mysql:host=$hostname;dbname=mysql"$username$password);
    
/*** echo a message saying we have connected ***/
    
echo 'Connected to database<br />';

    
/*** set the PDO error mode to exception ***/
    
$dbh->setAttribute(PDO::ATTR_ERRMODEPDO::ERRMODE_EXCEPTION);
    
    
/*** sql to create a user ***/
    
$sql "GRANT ALL ON periodic_table.* TO username@localhost IDENTIFIED BY 'password'";

    
/*** we use PDO::exec because no results are returned ***/
    
$dbh->exec($sql);

    
/*** echo a message to say the database was created ***/
    
echo 'Database created successfully<br />';
    }
catch(
PDOException $e)
    {
    
/*** echo the sql statement and error message ***/
    
echo $sql '<br />' $e->getMessage();
    }
?>

Creating a Table.

Now that a database has been created, and a database user other than root exists, we are able to connect to the database with our shiny new username and password. A database it really needs some data in it for it to be functional. For the purposes of this tutorial we are using the periodic table of elements, (we can all recite those from school, right?) so in our periodic_table database an appropriate table name would be elements. Lets first look at the SQL need to create such a table.


CREATE TABLE elements (
  atomicnumber tinyint(3) NOT NULL default '0',
  latin varchar(20) NOT NULL default '',
  english varchar(20) NOT NULL default '',
  abbr char(3) NOT NULL default '',
  PRIMARY KEY  (atomicnumber)
  )

Once again we can use code similar to that which we have already used to create a database and to create a new MySQL user. The same process is repeated here with the difference that we no longer need root access to be able to interface with our new database. The user "username" can be used and this is recommended practice. Never use root if you do not need it. Our new user has all the privileges needed to carry out any interactions with the database in this tutorial. With that in mind, lets get to table creation, first with the mysql extension functions.

Create table with mysql.


<?php

/*** mysql hostname ***/
$hostname 'localhost';

/*** mysql username ***/
$username 'username';

/*** mysql password ***/
$password 'password';

/*** connect to the database ***/
$link = @mysql_connect($hostname$username$password);

/*** check if the link is a valid resource ***/
if(is_resource($link))
    {
    
/*** if we are successful ***/
    
echo 'Connected successfully<br />';

    
/*** select the database we wish to use ***/
    
if(mysql_select_db("periodic_table"$link) === TRUE)
        {
        
/*** sql to create a new table ***/
        
$sql "CREATE TABLE elements (
        atomicnumber tinyint(3) NOT NULL default '0',
        latin varchar(20) NOT NULL default '',
        english varchar(20) NOT NULL default '',
        abbr char(3) NOT NULL default '',
        PRIMARY KEY  (atomicnumber)
        )"
;

        
/*** run the sql query ***/
        
if(mysql_query($sql$link))
            {
            echo 
'New table created successfully<br />';
            }
        else
            {
            echo 
'Unable to create table: <br />' $sql .'<br />' mysql_error();
            }
        }
    
/*** if we are unable to select the database show an error ***/
    
else
        {
        echo 
'Unable to select database';
        }
    
/*** close the connection ***/
    
mysql_close($link);
    }
else
    {
    
/*** if we fail to connect ***/
    
echo 'Unable to connect';
    }
?>

Lets go over what we have done here. We have used the CREATE TABLE statement to create a table called elements
Following that we have 4 fields that will contain the data itself. They are:
atomicnumber
latin
english
abbr
These fields will contain different data types and so have different attributes. The atomicnumber field has a type of tinyint or tiny interger and its maximum length is 3 with a default value of zero. More on types can be found in the MySQL documentation and is recommended reading.

Creating a Table with mysqli.

As with the script above, we no longer need to use the root username and password for creating our table. An extra parameter is added to our class instantiation that contains the name of the default database to use for our script. We assign this to a variable at the top of our script with the other variables.


<?php

/*** mysql hostname ***/
$hostname 'localhost';

/*** mysql username ***/
$username 'username';

/*** mysql password ***/
$password 'password';

/*** mysql database name ***/
$dbname 'periodic_table';

/*** create a new mysqli object with default database***/
$mysqli = @new mysqli($hostname$username$password$dbname);

/* check connection */ 
if(!mysqli_connect_errno())
    {
    
/*** if we are successful ***/
    
echo 'Connected Successfully<br />';

    
/*** sql to create a new table ***/
    
$sql "CREATE TABLE elements (
    atomicnumber tinyint(3) NOT NULL default '0',
    latin varchar(20) NOT NULL default '',
    english varchar(20) NOT NULL default '',
    abbr char(3) NOT NULL default '',
    PRIMARY KEY  (atomicnumber)
    )"
;


    if(
$mysqli->query($sql) === TRUE)
        {
        echo 
'New table created successfully<br />';
        }
    else
        {
        echo 
$sql.'<br />' $mysqli->error;
        }

    
/*** close connection ***/
    
$mysqli->close();
    }
else
    {
    
/*** if we are unable to connect ***/
    
echo 'Unable to connect';
    exit();
    }
?>

Creating a Table with PDO

The use of PDO will significantly cut down our code. Much of the savings comes from the use of exceptions rather than constantly checking for error conditions. As with the previous table creation examples we are now using a non-root username/password pair. We have also created a new variable called $dbname. This variable holds the name of the database we wish to connect to and is used when we instantiate a new PDO object like this:


<?php
  $dbh 
= new PDO("mysql:host=$hostname;dbname=$dbname"$username$password);
?>

With this in mind, our table creation script using PDO is as follows.


<?php

/*** mysql hostname ***/
$hostname 'localhost';

/*** mysql username ***/
$username 'username';

/*** mysql password ***/
$password 'password';

/*** database name ***/
$dbname 'periodic_table';

try {
    
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname"$username$password);
    
/*** echo a message saying we have connected ***/
    
echo 'Connected to database<br />';

    
/*** set the PDO error mode to exception ***/
    
$dbh->setAttribute(PDO::ATTR_ERRMODEPDO::ERRMODE_EXCEPTION);
    
       
$sql "CREATE TABLE elements (
        atomicnumber tinyint(3) NOT NULL default '0',
        latin varchar(20) NOT NULL default '',
        english varchar(20) NOT NULL default '',
        abbr char(3) NOT NULL default '',
        PRIMARY KEY  (atomicnumber)
        )"
;

    
/*** we use PDO::exec because no results are returned ***/
    
$dbh->exec($sql);

    
/*** echo a message to say the database was created ***/
    
echo 'Table created successfully<br />';
    }
catch(
PDOException $e)
    {
    
/*** echo the sql statement and error message ***/
    
echo $sql '<br />' $e->getMessage();
    }
?>

You should now have a database called "periodic" with a table named periodic within it. This table is has 4 fields and it is these that will contain the real data we wish to use. First we must INSERT some data into the tables.

INSERT data into MySQL

This will likely be the second most frequent task done with the database. All the data in the database needs to come from somewhere and it is done using the INSERT statement. The process is similar to what we have been doing with other SQL statements and should be familiar by now, so lets get to it...

INSERT data with mysql.


<?php

/*** mysql hostname ***/
$hostname 'localhost';

/*** mysql username ***/
$username 'username';

/*** mysql password ***/
$password 'password';

/*** connect to the database ***/
$link = @mysql_connect($hostname$username$password);

/*** check if the link is a valid resource ***/
if(is_resource($link))
    {
    
/*** if we are successful ***/
    
echo 'Connected successfully<br />';

    
/*** select the database we wish to use ***/
    
if(mysql_select_db("periodic_table"$link) === TRUE)
        {
        
/*** sql to INSERT a new record ***/
    
$sql "INSERT INTO elements (atomicnumber, latin, english, abbr)
        VALUES ( 1, 'HYDROGENIUM', 'Hydrogen', 'H')"
;

        
/*** run the sql query ***/
        
if(mysql_query($sql$link))
            {
            echo 
'New record created successfully<br />';
            }
        else
            {
            echo 
'Unable to INSERT data: <br />' $sql .'<br />' mysql_error();
            }
        }
    
/*** if we are unable to select the database show an error ***/
    
else
        {
        echo 
'Unable to select database';
        }
    
/*** close the connection ***/
    
mysql_close($link);
    }
else
    {
    
/*** if we fail to connect ***/
    
echo 'Unable to connect';
    }
?>

Now you should be getting in the swing of sending SQL to the database. It goes much the same for mysqli and PDO. We connect to the database server, then select the appropriate database, and issue commands. Lets continue with our mysqli example.

INSERT data with mysqli


<?php

/*** mysql hostname ***/
$hostname 'localhost';

/*** mysql username ***/
$username 'username';

/*** mysql password ***/
$password 'password';

/*** mysql database name ***/
$dbname 'periodic_table';

/*** create a new mysqli object with default database***/
$mysqli = @new mysqli($hostname$username$password$dbname);

/* check connection */ 
if(!mysqli_connect_errno())
    {
    
/*** if we are successful ***/
    
echo 'Connected Successfully<br />';

    
/*** sql to INSERT a new record ***/
    
$sql "INSERT INTO elements (atomicnumber, latin, english, abbr)
    VALUES ( 1, 'HYDROGENIUM', 'Hydrogen', 'H')"
;


    if(
$mysqli->query($sql) === TRUE)
        {
        echo 
'New record created successfully<br />';
        }
    else
        {
        echo 
$sql.'<br />' $mysqli->error;
        }

    
/*** close connection ***/
    
$mysqli->close();
    }
else
    {
    
/*** if we are unable to connect ***/
    
echo 'Unable to connect';
    exit();
    }
?>

Once again we have used the same code with just a different SQL statement. The process remains the same for commands that do not return a value or values.

INSERT data with PDO

Not to be out classed, PDO maintains a compact code base for perfoming the same task. Here we see the creation of the same record as above. Again we use the same script as creating the database and table. The only thing that changes is the SQL statement.


<?php

/*** mysql hostname ***/
$hostname 'localhost';

/*** mysql username ***/
$username 'username';

/*** mysql password ***/
$password 'password';

/*** database name ***/
$dbname 'periodic_table';

try {
    
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname"$username$password);
    
/*** echo a message saying we have connected ***/
    
echo 'Connected to database<br />';

    
/*** set the PDO error mode to exception ***/
    
$dbh->setAttribute(PDO::ATTR_ERRMODEPDO::ERRMODE_EXCEPTION);
    
    
/*** sql to INSERT a new record ***/
    
$sql "INSERT INTO elements (atomicnumber, latin, english, abbr)
        VALUES ( 1, 'HYDROGENIUM', 'Hydrogen', 'H')"
;

    
/*** we use PDO::exec because no results are returned ***/
    
$dbh->exec($sql);

    
/*** echo a message to say the database was created ***/
    
echo 'Recored created successfully<br />';
    }
catch(
PDOException $e)
    {
    
/*** echo the sql statement and error message ***/
    
echo $sql '<br />' $e->getMessage();
    }
?>

INSERT multiple records

In the previous section we can see how to INSERT a record into a database. This works fine for single records, but what if we have over one hundred records. The periodic table of elements holds one hundred and nine known elements. We need a method to INSERT all these records without needing one hundred and nine database queries. This would be a much to heavy drain on resources and time conusumin and time conusuming. The solution comes in several forms, depending on the extension you are using. We will step through each extension and see how the various INSERT methods compares. Lets get started with the mysql extention. MySQL provides a simple query method of handling multiple INSERTs.

INSERT multiple records with mysql


<?php

/*** mysql hostname ***/
$hostname 'localhost';

/*** mysql username ***/
$username 'username';

/*** mysql password ***/
$password 'password';

/*** connect to the database ***/
$link = @mysql_connect($hostname$username$password);

/*** check if the link is a valid resource ***/
if(is_resource($link))
    {
    
/*** if we are successful ***/
    
echo 'Connected successfully<br />';

    
/*** select the database we wish to use ***/
    
if(mysql_select_db("periodic_table"$link) === TRUE)
        {
        
/*** sql to INSERT multiple new records ***/
        
$sql "INSERT INTO elements (atomicnumber, latin, english, abbr)
        VALUES
    (1, 'HYDROGENIUM', 'Hydrogen', 'H'),
    (2, 'HELIUM', 'Helium', 'He'),
    (3, 'LITHIUM', 'Lithium', 'Li'),
    (4, 'Beryllium', 'Beryllium', 'Be'),
    (5, 'Borum', 'Boron', 'B'),
    (6, 'Carboneum', 'Carbon', 'C'),
    (7, 'Nitrogenium', 'Nitrogen', 'N'),
    (8, 'Oxygenium', 'Oxygen', 'O'),
    (9, 'Fluorum', 'Fluorine', 'F'),
    (10, 'Neon', 'Neon', 'Ne'),
    (11, 'Natrium', 'Sodium', 'Na'),
    (12, 'Magnesium', 'Magnesium', 'Mg'),
    (13, 'aluminium', 'Aluminum', 'Al'),
    (14, 'Silicium', 'Silicon', 'Si'),
    (15, 'Phosphorus', 'Phosphorus', 'P'),
    (16, 'Sulphur', 'Sulphur', 'S'),
    (17, 'Chlorum', 'Chlorine', 'Cl'),
    (18, 'Argon', 'argon', 'Ar'),
    (19, 'Kalium', 'Potassium', 'K'),
    (20, 'Calcium', 'Calcium', 'Ca'),
    (21, 'Scandium', 'Scandium', 'Sc'),
    (22, 'Titanium', 'Titanium', 'Ti'),
    (23, 'Vanadium', 'Vanadium', 'V'),
    (24, 'Chromium', 'Chromium', 'Cr'),
    (25, 'Manganum', 'Manganese', 'Mn'),
    (26, 'Ferrum', 'Iron', 'Fe'),
    (27, 'Cobaltum', 'Cobalt', 'Co'),
    (28, 'Niccolum', 'Nickel', 'Ni'),
    (29, 'Cuprum', 'Copper', 'Cu'),
    (30, 'Zincum', 'Zinc', 'Zn'),
    (31, 'Gallium', 'Gallium', 'Ga'),
    (32, 'Germanium', 'Germanium', 'Ge'),
    (33, 'Arsenicum', 'Arsenic', 'As'),
    (34, 'Selenium', 'Selenium', 'Se'),
    (35, 'Bromum', 'Bromine', 'Br'),
    (36, 'Krypton', 'Krypton', 'Kr'),
    (37, 'Rubidium', 'Rubidium', 'Rb'),
    (38, 'Strontium', 'Strontium', 'Sr'),
    (39, 'Yttrium', 'Yttrium', 'Y'),
    (40, 'Zirkonium', 'Zirkonium', 'Zr'),
    (41, 'Niobium', 'Niobium', 'Nb'),
    (42, 'Molybdaenum', 'Molybdaenum', 'Mo'),
    (43, 'Technetium', 'Technetium', 'Tc'),
    (44, 'Ruthenium', 'Ruthenium', 'Ru'),
    (45, 'Rhodium', 'Rhodium', 'Rh'),
    (46, 'Palladium', 'Palladium', 'Pd'),
    (47, 'Argentum', 'Silver', 'Ag'),
    (48, 'Cadmium', 'Cadmium', 'Cd'),
    (49, 'Indium', 'Indium', ' In'),
    (50, 'Stannum', 'Tin', 'Sn'),
    (51, 'Stibium', 'Antimony', 'Sb'),
    (52, 'Tellurium', 'Tellurium', 'Te'),
    (53, 'Iodum', 'Iodine', 'I'),
    (54, 'Xenon', 'Xenon', 'Xe'),
    (55, 'Caesium', 'Cesium', 'Cs'),
    (56, 'Baryum', 'Barium', 'Ba'),
    (57, 'Lanthanum', 'Lanthanum', 'La'),
    (58, 'Cerium', 'Cerium', 'Ce'),
    (59, 'Praseodymium', 'Praseodymium', 'Pr'),
    (60, 'Neodymium', 'Neodymium', 'Nd'),
    (61, 'Promethium', 'Promethium', 'Pm'),
    (62, 'Samarium', 'Samarium', 'Sm'),
    (63, 'Europium', 'Europium', 'Eu'),
    (64, 'Gadolinium', 'Gadolinium', 'Gd'),
    (65, 'Terbium', 'Terbium', 'Tb'),
    (66, 'Dysprosium', 'Dysprosium', 'Dy'),
    (67, 'Holmium', 'Holmium', 'Ho'),
    (68, 'Erbium', 'Erbium', 'Er'),
    (69, 'Thulium', 'Thulium', 'Tm'),
    (70, 'Ytterbium', 'Ytterbium', 'Yb'),
    (71, 'Lutetium', 'Lutetium', 'Lu'),
    (72, 'Hafnium', 'Hafnium', 'Hf'),
    (73, 'Tantalum', 'Tantalum', 'Ta'),
    (74, 'Wolframium', 'Tungsten', 'W'),
    (75, 'Rhenium', 'Rhenium', 'Re'),
    (76, 'Osmium', 'Osmium', 'Os'),
    (77, 'Iridium', 'Iridium', 'Ir'),
    (78, 'Platinum', 'Platinum', 'Pt'),
    (79, 'Aurum', 'Gold', 'Au'),
    (80, 'Mercury', 'Hydrargyrum', 'Hg'),
    (81, 'Thallium', 'Thallium', 'Tl'),
    (82, 'Plumbum', 'Lead', 'Pb'),
    (83, 'Bismuthum', 'Bismuth', 'Bi'),
    (84, 'Polonium', 'Polonium', 'Po'),
    (85, 'Astatium', 'Astatine', 'At'),
    (86, 'Radon', 'Radon', 'Rn'),
    (87, 'Francium', 'Francium', 'Fr'),
    (88, 'Radium', 'Radium', 'Ra'),
    (89, 'Actinium', 'Actinium', 'Ac'),
    (90, 'Thorium', 'Thorium', 'Th'),
    (91, 'Protactinium', 'Protactinium', 'Pa'),
    (92, 'Uranium', 'Uranium', 'U'),
    (93, 'Neptunium', 'Neptunium', 'Np'),
    (94, 'Plutonium', 'Plutonium', 'Pu'),
    (95, 'Americium', 'Americium', 'Am'),
    (96, 'Curium', 'Curium', 'Cm'),
    (97, 'Berkelium', 'Berkelium', 'Bk'),
    (98, 'Californium', 'Californium', 'Cf'),
    (99, 'Einsteinium', 'Einsteinium', 'Es'),
    (100, 'Fermium', 'Fermium', 'Fm'),
    (101, 'Mendelevium', 'Mendelevium', 'Md'),
    (102, 'Nobelium', 'Nobelium', 'No'),
    (103, 'Lawrencium', 'Lawrencium', 'Lr'),
    (104, 'Rutherfordium', 'Rutherfordium', 'Rf'),
    (105, 'Dubnium', 'Dubnium', 'Db'),
    (106, 'Seaborgium', 'Seaborgium', 'Sg'),
    (107, 'Bohrium', 'Bohrium', 'Bh'),
    (108, 'Hassium', 'Hassium', 'Hs'),
    (109, 'Meitnerium', 'Meitnerium', 'Mt')
    "
;

        
/*** run the sql query ***/
        
if(mysql_query($sql$link))
            {
            echo 
'New record created successfully<br />';
            }
        else
            {
            echo 
'Unable to INSERT data: <br />' $sql .'<br />' mysql_error();
            }
        }
    
/*** if we are unable to select the database show an error ***/
    
else
        {
        echo 
'Unable to select database';
        }
    
/*** close the connection ***/
    
mysql_close($link);
    }
else
    {
    
/*** if we fail to connect ***/
    
echo 'Unable to connect';
    }
?>

The above code will populate the elements table with all one hundred and nine elements. This is far superior to one hundred and nine seperate INSERT statements and database connections. Be aware that of the Max Allowed Packet size as large SQL statements of several thousand INSERTs or BLOBs may breach this limit.

INSERT multiple records with mysqli

The mysqli extenstion provides an object oriented approach to the same task. The mysqli extension contains a class method named multi_query() for exactly this purpose. This class method basically takes an SQL statement, or multiple SQL statements concatenated by a semicolon ; character. Lets see it in action with a small subset of our periodic table of elements. We use a subset because I had to type that first lot out and it took me hours ...


<?php

/*** mysql hostname ***/
$hostname 'localhost';

/*** mysql username ***/
$username 'username';

/*** mysql password ***/
$password 'password';

/*** mysql database name ***/
$dbname 'periodic_table';

/*** create a new mysqli object with default database***/
$mysqli = @new mysqli($hostname$username$password$dbname);

/* check connection */ 
if(!mysqli_connect_errno())
    {
    
/*** if we are successful ***/
    
echo 'Connected Successfully<br />';

    
/*** sql to INSERT a new record ***/
    /*** note the semi colon on the end of each statement ***/
    
$sql  "INSERT INTO elements (atomicnumber, latin, english, abbr) VALUES ( 1, 'HYDROGENIUM', 'Hydrogen', 'H');";
    
$sql .= "INSERT INTO elements (atomicnumber, latin, english, abbr) VALUES ( 2, 'HELIUM', 'Helium', 'He');";
    
$sql .= "INSERT INTO elements (atomicnumber, latin, english, abbr) VALUES ( 3, 'LITHIUM', 'Lithium', 'Li')";
    
$sql .= "INSERT INTO elements (atomicnumber, latin, english, abbr) VALUES ( 4, 'BERYLLIUM', 'Beryllium', 'Be');";
    
$sql .= "INSERT INTO elements (atomicnumber, latin, english, abbr) VALUES ( 5, 'BORUM', 'Boron', 'B')";


    
/*** run the multiple statements and check for errors ***/
    
if($mysqli->multi_query($sql) !== FALSE)
        {
        echo 
'New records created successfully<br />';
        }
    else
        {
        echo 
$sql.'<br />' $mysqli->error;
        }

    
/*** close connection ***/
    
$mysqli->close();
    }
else
    {
    
/*** if we are unable to connect ***/
    
echo 'Unable to connect';
    exit();
    }
?>

The above, shortened INSERT will work for the whole table and it is left as an exercise for the reader to complete the table. The mysqli extension provides a second method for achieving the same result for multiple INSERT. We can also use prepared statements and bind parameters. The mysql extension can send a statement or query without any data to the mysql database. You can then associate or "bind" variables to the columns.


<?php

/*** mysql hostname ***/
$hostname 'localhost';

/*** mysql username ***/
$username 'username';

/*** mysql password ***/
$password 'password';

/*** mysql database name ***/
$dbname 'periodic_table';

/*** create a new mysqli object with default database***/
$mysqli = @new mysqli($hostname$username$password$dbname);

/* check connection */ 
if(!mysqli_connect_errno())
    {
    
/*** if we are successful ***/
    
echo 'Connected Successfully<br />';

    
/*** Create the SQL statement ***/
    
$sql 'INSERT INTO elements VALUES(?, ?, ?, ?)';

    
/*** Initialize a statement object for mysqli_stmt_prepare() ***/
    
$stmt mysqli_stmt_init($mysqli);

    
/*** prepare our statement ***/
    
if (mysqli_stmt_prepare($stmt$sql))
        {
        
/*** bind the parameters ***/
          
mysqli_stmt_bind_param($stmt'isss'$atomicnumber$latin$english$abbr);
  
          
/*** set parameters and execute ***/
          
$atomicnumber 1;
          
$latin 'Hydrogenium';
          
$english 'Hydrogen';
          
$abbr 'H';
        
mysqli_stmt_execute($stmt);
  
        
/*** set parameters and execute ***/
        
$atomicnumber 2;
        
$latin 'Helium';
        
$english 'Helium';
        
$abbr 'He';
        
mysqli_stmt_execute($stmt);
        
        
/*** set parameters and execute ***/
        
$atomicnumber 3;
        
$latin 'Lithium';
        
$english 'Lithium';
        
$abbr 'Li';
        
mysqli_stmt_execute($stmt);

        
/*** set parameters and execute ***/
        
$atomicnumber 4;
        
$latin 'Beryllium';
        
$english 'Beryllium';
        
$abbr 'Be';
        
mysqli_stmt_execute($stmt);

        
/*** set parameters and execute ***/
        
$atomicnumber 5;
        
$latin 'Borum';
        
$english 'Boron';
        
$abbr 'B';
        
mysqli_stmt_execute($stmt);
        }
    }
else
    {
    
/*** if we are unable to connect ***/
    
echo 'Unable to connect';
    exit();
    }
?>

We see above a more modular solution to the issue. We can create code blocks also that are easy to read and easy to manage. Just a note on binding parameters. Lets examine the mysqli_stmt_bind_param() line of code...


mysqli_stmt_bind_param($stmt, 'isss', $atomicnumber, $latin, $english, $abbr);

This function binds the parameters to the query and tells the database what the parameters are. Next is the "isss" arguement. This listes the types of data that the parameters are. The i tells mysql that the parameter is an integer. The s character tells mysql that the parameter is a string. This arguement may be one of four types.

  • i - integer
  • d - double
  • s - string
  • b - BLOB

You must have one of these for each parameter. Prepared statements separate data from logic, thereby aiding us in our quest for secure data. By telling mysql what type of data to expect we can help minimise the risk of SQL injection vulnerabilities in our code. Should any values from external sources be used it is critical that they be sanitized and validated. More on this topic later...

INSERT multiple records with PDO

If you have followed the previous example with mysqli, the step to using PDO is small. The PDO interface allows us to use bound parameters and prepared statements also. The great benifit of PDO is exceptions and use of arrays for queries. For multiple a mulitple INSERT statement would could use an array as a parameter. The PDO interface will also give easy access to the use of transactions. In the following example we will see how to quickly deal with a multiple INSERT. Once again we will use only a small portion of the table to demonstrate for obvious reasons.


<?php

/*** mysql hostname ***/
$hostname 'localhost';

/*** mysql username ***/
$username 'username';

/*** mysql password ***/
$password 'password';

/*** database name ***/
$dbname 'periodic_table';

try {
    
$dbh = new PDO("mysql:host=$hostname;