Free web design training service and resources by the Rochester Web Wizard @ Data Info Magic

Free web design training guide and resources by the Rochester Web Wizard. Sponsored by Data Info Magic.

Lesson 6 : Combining PHP & MySQL

MySQL is a relational database management system (RDBMS) which has more than 6 million installations. The program runs as a server providing multi-user access to a number of databases.

The project's source code is available under terms of the GNU General Public License, as well as under a variety of proprietary agreements. MySQL is owned and sponsored by a single for-profit firm, the Swedish company MySQL AB, now a subsidiary of Sun Microsystems, which holds the copyright to most of the codebase.

MySQL is commonly used by free software projects which require a full-featured database management system, such as WordPress, phpBB and other software built on the LAMP software stack. It is also used in very high-scale World Wide Web products including Google and Facebook.

To get started with writing MySQL queries, try writing your first MySQL query. You really need to strongly consider purchasing a reference book. The best book resource for PHP is the Sams Teach Yourself MySQL in 10 Minutes by Chris Newman. It is inexpensive (less than $20) short and consice. It is available almost anywhere books are sold including Amazon and Barnes & Noble online. This is the only reference book you will ever need for MySQL code.

 

Reminder: You need to have XAMMP including the Apache Server and PHP installed and running to try PHP locally. Your HostMonster account already has Apache Server and PHP set up and ready to go but you need to request setup for a MySQL database. For other Hosts you will need to check on their particular procedure and whether they support it. All you need to do is change the file extention to .php and add your PHP code to the HTML. A PHP page can still run HTML code. You just nee to start <? and stop ?> the PHP code.

Important Tip: Even though MySQL code is not case sensitive nor does it require indenting, make sure to follow the conventions for readability, especially for yourself.

 

 

PHP and MySQL are made for each other!

You can use PHPMyAdmin or DreamCoder to check the values of the database tables as you go along.You can get the necessary information to connect from your hosting company.

First you will need to learn to create a database, create a table in it, create columns and properties for your table and add data.

Next you will need to run queries on your table with various outputs.

The 4 items that you must always know when dealing with a database on the local server (Apache installed on your machine) are:

1. Host is localhost

2. User Name is root

3. Password is can be left blank on the local machine so don't enter one initially.

4. Database name is whatever you choose and Table is also. One database may have many tables.

They can be the same on the remote server (The server set up by HostMonster or your current hosting company), except ALWAYS USE A PASSWORD AND SET YOUR USER PERMISSIONS AS STRICTLY AS POSSIBLE!!!!!

You can go through all of the examples in the Sams Teach Yourself MySQL in 10 Minutes pretty rapidly, but it will probably take considerably more than 10 minutes! To save you time, I have compiled most of them in one document below. Each statement is meant to be executed individually. You can also use DreamCoder to speed things up but hold off until you know how to wite the code directly first. You will use the Exact Same Code in your PHP code later.

You can learn to make the forms and PHP/MySQL separately first. I have a tutorial for that there is already a free one available that I used at Database Samples. I furnish most of the code for you to use and working applications to try. I take it really slow but it's a good way to review what you've done so far. It only covers the basics but in a very clear and simple way. This is a good intermediate step if you have no database experience or you aren't a programmer. The examples do not touch on any kind of MySQL security so they are not appropriate for online use. You should only test these on your local server.

These demonstrations use a database, test. with the several tables. You can use 2 different files dbinfo.inc.php and dbinfo2.inc.php one for your local machine and one for the remote host. Then you only need to change 1 line of code in each file before uploading to your host server. The code should look like this:

<?/* local or remote connection*/
$server="localhost";
$username="your user name";
$password="your password";
$database="test";
?>

Then in each file put in the lines:

include ("dbinfo.inc.php");
$db=@mysql_connect($server,$username,$password);
if(!($db))
{
echo "Connection failed.";
exit;
}
$dbn=@mysql_select_db($database);
if(!($dbn))
{
echo "Database not found.";
exit;
}

You can get the script to create the tables for the database here: test script

Most of the code is also furnished below if you want to set it up yourself. Between the 2 it shouldn't be hard to catch on.

If you want to try MySQL/PHP programs on HostMonster now: You will need to request the setup of your MySQL database. It will include up to 99 databases for free with no size limit! Log into your account. On the CPanel page you will see your username. Every database name and MySQL user will begin with this prefix "username_". Do not enter it when naming your databases or users. It will be appended automatically. It will save you time if you use the same convention on your local server so you don't need to change any code when you upload your PHP files. Never have any user enter a username or database name with the prefix. Use PHP concantenation to append it after it is entered. Towards the bottom of the CPanel you will see the Datbases panel:

CPanel

You will use the phpMyAdmin application exactly the same way as your local machine. The exception is when you create a new database and users with permissions. That happens at the MySQL Databases application. The easiest way to transfer your MySQL local files to your server or vise versa is to dump your database to a .sql file and copy and run the script in the SQl window of phpMyAdmin on either server or DreamCoder for MySQL on your local machine.

 

 

 

 

MySQL Database Management System

Using either DreamCoder or PHPMyAdmin, create a database named test. Create a project folder called MySQL Project. Create an images folder inside.


Create Table

Make a simple HTML page with a CSS file attached. Save the file as create.php. Make sure the file extension is .php. Use the server, username and password that you set up on your local server. Change them in the code if necessary. These values must match!

Repeat these steps for each of the following pages using the corresponding name.

In create.php, add the following code in the body:

<?
$username="root";
$password="";
$database="test";
mysql_connect("localhost", $username, $password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());

// Create a MySQL table in the selected database
mysql_query("CREATE TABLE family(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
position VARCHAR(30),
age VARCHAR(30))")
or die(mysql_error());
echo "Table family Created!";
?>

(You can only run this once.)

Insert Values

In insert.php, add the following code in the body:

<?
$username="root";
$password="";
$database="test";
mysql_connect("localhost", $username, $password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());

// Insert a row of information into the table "example"
mysql_query("INSERT INTO example
(name, age) VALUES('Timmy Mellowman', '23' ) ")
or die(mysql_error());
mysql_query("INSERT INTO example
(name, age) VALUES('Sandy Smith', '21' ) ")
or die(mysql_error());
mysql_query("INSERT INTO example
(name, age) VALUES('Bobby Wallace', '15' ) ")
or die(mysql_error());
echo "Data Inserted!";
?>


Minimum Value

In min.php, add the following code in the body:

<?
$username="root";
$password="";
$database="test";
mysql_connect("localhost", $username, $password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());

// Get all the data from the "example" table
$result = mysql_query("SELECT * INTO OUTFILE 'result.csv'FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'LINES TERMINATED BY '\n'FROM example")
or die(mysql_error());

echo "<table border='2'>";
echo "<tr> <th>id</th> <th>name</th> <th>type</th> <th>price</th>
</tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['id'];
echo "</td><td>";
echo $row['name'];
echo "</td><td>";
echo $row['type'];
echo "</td><td>";
echo $row['price'];
echo "</td></tr>";
}
echo "</table>";

$query = "SELECT type, MIN(price) FROM products GROUP BY type";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo $row['type']. " - $". $row['MIN(price)'];
echo "<br />";
}
?>

Try max.php next.


Table Values

In table.php, add the following code in the body:

<?
$username="root";
$password="";
$database="test";
mysql_connect("localhost", $username, $password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());

// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM example")
or die(mysql_error());

echo "<table border='2'>";
echo "<tr> <th>Name</th> <th>Age</th>
</tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['name'];
echo "</td><td>";
echo $row['age'];
echo "</td></tr>";
}
echo "</table>";
?>


Update Values

Create a new table named example withid (int) name (varchar) and age (int) columns. Add 5 people with ages ranging from 20 through 30. Make sure at least one has age 21.

In update.php, add the following code in the body:

<?
$username="root";
$password="";
$database="test";
mysql_connect("localhost", $username, $password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());
// Get Sandy's record from the "example" table
$result = mysql_query("UPDATE example SET age='22' WHERE age='21'")
or die(mysql_error());

// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM example WHERE age='22'")
or die(mysql_error());

echo "<table border='2'>";
echo "<tr> <th>Name</th> <th>Age</th>
</tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['name'];
echo "</td><td>";
echo $row['age'];
echo "</td></tr>";
}
echo "</table>";
?>


Insert Values

In insert.php, add the following code in the body:

<?
$username="root";
$password="";
$database="test";
mysql_connect("localhost", $username, $password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());


mysql_query("INSERT INTO example
(name, age) VALUES('Timmy Mellowman', '23' ) ")
or die(mysql_error());
mysql_query("INSERT INTO example
(name, age) VALUES('Sandy Smith', '21' ) ")
or die(mysql_error());
mysql_query("INSERT INTO example
(name, age) VALUES('Bobby Wallace', '15' ) ")
or die(mysql_error());
echo "Data Inserted!";
?>


Order Values

In order.php, add the following code in the body:

<?
$username="root";
$password="jcrdb";
$database="test";
mysql_connect("localhost", $username, $password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());


$result = mysql_query("SELECT * FROM example ORDER BY age")
or die(mysql_error());

echo "<table border='2'>";
echo "<tr> <th>Name</th> <th>Age</th>
</tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['name'];
echo "</td><td>";
echo $row['age'];
echo "</td></tr>";
}
echo "</table>";
?>


Count Values

Create the products table:

/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
DROP TABLE IF EXISTS `test`.`products`;
CREATE TABLE `test`.`products` (
`id` varchar(30) NOT NULL default '',
`name` varchar(60) NOT NULL default '',
`type` varchar(30) NOT NULL default '',
`price` decimal(10,2) NOT NULL default '0.00',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;

Add the values:

INSERT INTO PRODUCTS
(id,name,type,price)
VALUES('123451','Park''s Great Hits','Music',19.99);

INSERT INTO PRODUCTS
(id,name,type,price)
VALUES('123452','Silly Puddy','Toy',3.99);

INSERT INTO PRODUCTS
(id,name,type,price)
VALUES('123453','Playstation','Toy',89.95);

INSERT INTO PRODUCTS
(id,name,type,price)
VALUES('123454','Men''s T-Shirt','Clothing',32.5);

INSERT INTO PRODUCTS
(id,name,type,price)
VALUES('123455','Blouse','Clothing',34.97);

INSERT INTO PRODUCTS
(id,name,type,price)
VALUES('123456','Electronica 2002','Music',3.99);

INSERT INTO PRODUCTS
(id,name,type,price)
VALUES('123457','Country Tunes','Music',21.55);

INSERT INTO PRODUCTS
(id,name,type,price)
VALUES('123458','Watermelon','Food',8.73);

In count.php, add the following code in the body:

<?
$username="root";
$password="";
$database="test";
mysql_connect("localhost", $username, $password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());

// Get all the data from the "products" table
$result = mysql_query("SELECT * FROM products")
or die(mysql_error());

echo "<table border='2'>";
echo "<tr> <th>id</th> <th>name</th> <th>type</th> <th>price</th>
</tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['id'];
echo "</td><td>";
echo $row['name'];
echo "</td><td>";
echo $row['type'];
echo "</td><td>";
echo $row['price'];
echo "</td></tr>";
}
echo "</table>";
$query = "SELECT type, COUNT(name) FROM products GROUP BY type";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "There are ". $row['COUNT(name)'] ." ". $row['type'] ." items.";
echo "<br />";
}
?>


Average Values

In average.php, add the following code in the body:

<?
$username="root";
$password="";
$database="test";
mysql_connect("localhost", $username, $password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());

// Get all the data from the "products" table
$result = mysql_query("SELECT * FROM products")
or die(mysql_error());

echo "<table border='2'>";
echo "<tr> <th>id</th> <th>name</th> <th>type</th> <th>price</th>
</tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['id'];
echo "</td><td>";
echo $row['name'];
echo "</td><td>";
echo $row['type'];
echo "</td><td>";
echo $row['price'];
echo "</td></tr>";
}
echo "</table>";
$query = "SELECT type, AVG(price) FROM products GROUP BY type";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "The average price of ". $row['type']. " is $".$row['AVG(price)'];
echo "<br />";
}
?>


Sum Values

In sum.php, add the following code in the body:

<?
$username="root";
$password="";
$database="test";
mysql_connect("localhost", $username, $password) or die(mysql_error());
mysql_select_db($database) or die(mysql_error());

// Get all the data from the "products" table
$result = mysql_query("SELECT * FROM products")
or die(mysql_error());

echo "<table border='2'>";
echo "<tr> <th>id</th> <th>name</th> <th>type</th> <th>price</th>
</tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['id'];
echo "</td><td>";
echo $row['name'];
echo "</td><td>";
echo $row['type'];
echo "</td><td>";
echo $row['price'];
echo "</td></tr>";
}
echo "</table>";
$query = "SELECT type, SUM(price) FROM products GROUP BY type";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "Total ". $row['type']. " = $". $row['SUM(price)'];
echo "<br />";
}
?>

 

 

Don't stop now!!!

Make an index page with a menu where you can choose any option. Keep in mind that these samples contain No Security and should not be used on the Internet without adding at least code for SQL Injection.

You can look at the sample database and have a much better idea of what is happening. The database application contains full AJAX security. You will be required to log in to access the Database Application.There are many more advanced queries in the reference book. You will quickly get the hang of the syntax.

 

 

Warning: It is tedious and extremely time consuming as well as confusing at first to add the necessary security to your MySQL. It is absolutely necessary before you start putting any databses on the Host Server and available on the Internet. The exception is when you are learning and don't actually have any valuable data.

Looking Ahead: Next we will add forms, security and a menu and combine all of the topics into one comprehensive project. You should now look into HTML Forms so that you can enter, delete, update and print tables from your database. It isn't difficult to put the two things together. Here's a place to start: PHP Forms Tutorial.

Go on to Lesson 7 (Available Now!)

 
Back to Main Menu