MySQL Quick Reference Guide for Class

advertisement
MySQL
Databases and Tables
The database can contain one or more "tables." Tables are what we would normally
conceptualize as a database in psychology. A table is a row by column matrix in which you
might organize a person's data in rows, with each piece of information represented in a separate
column.
When multiple tables exist in a common database, it is possible to link information across tables.
For example, you might have a complex project in which the same users potentially complete
multiple studies on your website. If so, the data for each study might be represented in distinct
tables, but all those tables might be part of a common database. Moreover, you might have a
separate table that contains detailed background information on the users (e.g., age, sex, location)
so that the information does not have to be re-represented in each individual study's table.
Some "rules" regarding the names or identifiers used for databases and tables




should only contain letters and numbers. No spaces. Avoid fancy symbols.
names are case sensitive
it should be unique
it should not conflict with existing functions or keywords (e.g., CREATE).
Variable types



text/strings
numbers
dates/times
There are a lot of data types available in SQL. For the most part, you can simplify your life
by working with the previous three. Here are some specific examples:


VARCHAR(20) -- variable length field from 0 to 65,535 characters long
CHAR(40) -- set of characters (letters or numbers) of maxlength 40


DATETIME -- format of YYYY-MM-DD HH:MM:SS
MEDIUMTEXT -- holds text up to 16,777,215 characters
Good summary here:
http://www.w3schools.com/sql/sql_datatypes.asp
Keys
A primary key is a way to refer to a particular record in a table. It must adhere to the following:
1. It must always have a positive value (UNSIGNED, NOT NULL).
2. That value must never change.
3. That value must be unique--each record needs its own primary key that is distinct from
all others.
The easiest way to do this is to designate as a primary key a variable, such as user_id, and allow
it to AUTO_INCREMENT. Thus, each time a new record is added to the table, the record will be
assigned a value automatically without you having to fret about it.
phpMyAdmin
It is easiest to create and work with your SQL database via an application (written in PHP) called
phpMyAdmin.
1. Login to your Netfirms Control Panel
2. Choose the option labeled "MySQL Database"
3. This will display a list of existing databases (if you have some already).
To create a new database, select the icon that has a plus sign on it. If you mouseover it, it will
read "Add Database".
4. You will need to complete the following fields:




Database Name:
Username:
Password:
Confirm Password:
Chose a database name that is short, self-descriptive, with no spaces. Your username should be
self-descriptive too without complicated characters or spaces. Choose a password. WRITE
DOWN ALL THIS INFORMATION IN A PLACE WHERE YOU WILL NOT LOSE IT.
5. The new database should be listed in the left-side of the display window.
If you select it, you will see a number of options in the right-side of the window. Two of these
will be needed:
5a. Access phpMyAdmin
This will be used to control the database. Via this application, you can add tables to the database,
view the contents of the tables, and update by hand anything you might need to modify.
5b. Generate Code
This nice option will generate for you the PHP code you will need to login into the database and
control it within your PHP scripts.
Example:
Your Server Name:
Database Name:
yourpersonality.netfirmsmysql.com
class
Database Username: rcfraley
Database Password: ********
Here is the resulting code.
<?php
$link = mysql_connect('yourpersonality.netfirmsmysql.com', 'rcfraley',
'*password*');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db(class);
?>
You need to replace the *password* with your password in your PHP scripts.
Let's explore phpMyAdmin
In many cases you can paste SQL commands into the window by clicking the SQL tab. Once the
database has been created, we can add TABLEs to it. These are the data files that we care most
about.
CREATE TABLE users (
user_id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
first_name VARCHAR(20) NOT NULL,
last_name VARCHAR(40) NOT NULL,
email VARCHAR(60) NOT NULL,
pass CHAR(40) NOT NULL,
registration_date DATETIME NOT NULL,
PRIMARY KEY (user_id)
);
We can view the new table via the browse "structure" option.
Let's add some data for the sake of populating our table.
INSERT INTO users
(first_name, last_name, email, pass, registration_date)
VALUES ('Chris', 'Fraley', 'rcfraley@gmail.com', SHA1('password'), NOW());
Notice that the user_id variable auto-increments when we browse the data.
Let's add multiple rows at once:
INSERT INTO users
(first_name, last_name, email, pass, registration_date) VALUES
('Garrett', 'Fraley', 'rcfraley@gmail.com', SHA1('passwordg'), NOW()),
('Mary', 'Fraley', 'rcfraley@gmail.com', SHA1('passwordm'), NOW());
Let's update a cell of the table
UPDATE users SET email='mary@rcfraley.com' WHERE user_id = 2;
Maybe we need to delete a record! Using LIMIT 1 helps ensure that only one case gets deleted.
There should not be a problem with the code sans this caveat, but we might as well be
conservative when using DELETE.
DELETE FROM users WHERE user_id = 3 LIMIT 1;
Notice what happens to user_id when we delete and then add a new case.
INSERT INTO users
(first_name, last_name, email, pass, registration_date)
VALUES ('Garrett', 'Fraley', 'rcfraley@gmail.com', SHA1('passwordg'), NOW());
Selecting data from a table
SELECT * FROM users;
SELECT first_name, last_name FROM users;
Using Conditionals
SELECT first_name from users
WHERE user_id=1;
(Can use familiar PHP style conditionals, for the most part: =, >, <, >=, <=, !=, OR, AND,
NOT)
SELECT first_name from users
WHERE email='rcfraley@gmail.com';
Sorting results
SELECT first_name from users
ORDER by first_name DESC;
DESC is optional. Ascending would be the default.
Accessing the database via PHP
Open a connection to the database.
<?php
// Set
DEFINE
DEFINE
DEFINE
DEFINE
the database access information as constants:
('DB_USER', 'rcfraley');
('DB_PASSWORD', '*password*');
('DB_HOST', 'yourpersonality.netfirmsmysql.com');
('DB_NAME', 'class');
// Make the connection:
$dbc = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die
('Could not connect to MySQL: ' . mysqli_connect_error() );
?>
and eventually, close the connection.
mysqli_close($dbc); // Close the database connection.
Create the query as a string. (Makes things easier, as a general rule.) Then run the query.
$q= "UPDATE users SET email='changed@rcfraley.com' WHERE user_id=2
LIMIT 1";
$r = @mysqli_query ($dbc, $q); // Run the query.
Download