Home > Web Servers & Systems > Introduction to MySQL

Introduction to MySQL

July 17, 2012

MySQL runs on a server deamon where users on the same or even remote computers can connect.
Once connected you can select database if you have privileges to do so.
In this tutorial you will learn:
1. How to connect to MySQL.
2. Create a Table
3. Insert data in to you database.
4. Display database data in you browser.
5. Change data.

The Code:
Lets start off by connecting to MySQL:

<?php
= "localhost";
= "username";
= "password";
= "database";

= mysql_connect("","","");
if (!
) die ("Could not connect MySQL");
mysql_select_db(,) or die ("Could not open database");

What I’ve done here is just to set all the variables, you don’t have to do this but it looks
better and it’s much easier to see what you are doing once the code starts to get big.
If you’d put = mysql_connect(“127.0.0.1″,”morgan”,”548641845″); it would
work just fine.
if(!) checks if there is an connection, if not display an error message, same with
mysql_select_db if he doesn’t find the database an error message will be displayed.
Now lets create a table:

mysql_query("CREATE TABLE users (
firstname VARCHAR(20),
surname VARCHAR(20),
location VARCHAR(20))"
);

you will get to use mysql_query quite alot once you start using MySQL alot. This line is pretty straight forward, we are
creating a table called users and then we add 3 columns to it, VARCHAR(20) allows an input of maximum 20 characters.

Once you are connected to MySQL and your table is set up you might want to
add some data to your table, for the moment it looks like this:

firstname surname location

now we want to put some data in to it and make it look like this:

firstname surname location
Morgan Andersson UK

 

= "INSERT INTO users (firstname,surname,location)
VALUES ('Morgan','Andersson','UK')"
;
mysql_query() or die ("Could not add data to the table");

 

Now lets add another piece of code to list the data in your browser:

= "SELECT * FROM users";
= mysql_query();
= mysql_num_rows();
while(
= mysql_fetch_array()){
echo
"You have user(s) in the database";
echo
"First Name: [firstname]";
echo
"Surname: [surname]";
echo
"Location: [location]";
}

The code above should display:
You have 1 user(s) in the database
First Name: Morgan
Surname: Andersson
Location: UK

Easy? Now lets change UK to SWEDEN:

= "UPDATE users SET location='SWEDEN' WHERE location='UK'";
= mysql_query();

Now lets see if it worked:

= "SELECT * FROM users";
= mysql_query();
while(
= mysql_fetch_array()){
echo
"Location is now: [location]";
}
?>

When all is done you should have this in your browser:

You have 1 user(s) in the database
First Name: Morgan
Surname: Andersson
Location: UK

Location is now: SWEDEN


By Morgan Andersson

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: