Database manipulation
Introduction to the PHP/SQL Connection
A full stack website consists of three layers.
Instructions are on the resources page
phpMyAdmin
link
Note for those using Ubuntu 18.04 and MAMP:
Here
is the fix if you see an error that says
count(): Parameter must be an array or an object that implements Countable
You can also use MySQL from the command line, if you're interested please come see us during office hours.
Each MySQL server can have multiple databases.
CREATE DATABASE database_name;
creates a new database
SHOW DATABASES;
displays a list of the databases
USE database_name;
selects a database for use
CREATE TABLE
CREATE TABLE is used to create a new table.
Syntax:
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY(one or more columns)
);
What kinds of information would you need if you were going to plan a potluck meal?
This might include
CREATE TABLE
exampleCREATE TABLE Potluck(
id INT,
name VARCHAR(255),
dish VARCHAR(255),
serves INT,
temperature VARCHAR(255),
PRIMARY KEY(id)
);
A full list of data types are here.
Data Type | Desription |
CHAR(size) | Holds a fixed length string. The fixed size is specified in parenthesis. Can store up to 255 characters |
VARCHAR(size) | Holds a variable length string. The maximum size is specified in parenthesis. Can store up to 255 characters, if you have more, use TEXT. |
TINYTEXT | Holds a string with a maximum length of 256 characters |
TEXT | Holds a string with a maximum length of 65,535 characters |
INT(size), TINYINT(size), BIGINT(size) | -2147483648 to 2147483647 normal. 0 to 4294967295 UNSIGNED*. The maximum number of digits may be specified in parenthesis |
FLOAT(size,d), DOUBLE(size, d) | A small or large number with a floating decimal point. The maximum number of digits may be specified in the size parameter. The maximum number of digits to the right of the decimal point is specified in the d parameter |
DATE(), DATETIME() | A date or time and date format. |
SHOW TABLES;
displays a list of the tables
DESCRIBE table_name;
display the columns of the table
DROP TABLE table_name;
deletes a table
DROP TABLE IF EXISTS table_name;
deletes a table only
if it exists, which prevents an error if it doesn't
INSERT
INSERT is used to insert a new record into an existing table.
Syntax:
INSERT INTO Potluck (id, name, dish, serves, temperature )
VALUES (1, "Lauren", "Paleo Apple Tart", 8, "room");
INSERT INTO Potluck (id, name, dish, serves, temperature )
VALUES (2, "Stephen", "Balsamic Brussels Sprouts", 8, "hot");
INSERT INTO Potluck (id, name, dish, serves, temperature )
VALUES (3, "Elias", "Apple Pie", 8, "room");
INSERT
ing many rowsYou can insert many rows at once by doing this:
INSERT INTO Potluck (id, name, dish, serves, temperature )
VALUES
(4, "Kristina", "Broccoli Salad", 16, "cold"),
(5, "Ron and Jacki", "Turkey", 20, "hot"),
(6, "Ron and Jacki", "Stuffing", 16, "hot"),
(7, "Matthew", "Drinks", 16, "cold"),
(8, "Ron", "Mashed Potatoes", 12, "hot"),
(9, "Ron", "Green Bean Casserole", 16, "hot"),
(10, "Audrey", "Baked Brie", 10, "hot"),
(11, "Sadie", "Dog food", 1, "room");
UPDATE
UPDATE table
SET col1 = val1, col2 = val2, ...
WHERE condition;
UPDATE Potluck
SET dish = "Mashed Potato Casserole", name = "Stephen"
WHERE dish = "Mashed Potatoes";
UPDATE changes all rows where the condition is true.
DELETE
DELETE FROM table
WHERE condition;
DELETE FROM Potluck
WHERE name = "Sadie";
Deletes the specified records based on the results of the WHERE clause
CAUTION: if you omit the WHERE clause all records will be deleted!!!
PDO
classThere are two ways to connect to a database through PHP
We are using PDO in this class
To connect to a database you need 4 pieces of information
Then create a PDO
object to represent the database connection
# Variables for connections to the database.
$host = 'localhost'; #fill in with server name
$port = '' #fill in with a port if necessary (will be different mac/pc)
$dbname = 'Potluck'; #fill in with db name
$user = 'root'; #fill in with user name
$password = ''; #fill in with password (will be different mac/pc)
# Make a data source string that will be used in creating the PDO object
$ds = "mysql:host={$host}:{$port};dbname={$dbname};charset=utf8";
# connect to the Potluck database and set some attributes
$db = new PDO($ds, $user, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
To find find out what to use with phpMyAdmin, check out the MAMP WebStart page. For other systems you have to do searching on the web.
try
/catch
Database connections can have different problems: the database server could be down, the database could be missing or corrupted
try
/catch
helps us catch and
identify when errors occur so we can handle the error correctly
try {
# things to try that could throw an error
}
catch (PDOException $ex) {
# code for handling the error here.
}
try
/catch
example
try {
$db = new PDO($ds, $user, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $ex) {
header("HTTP/1.1 400 Invalid Request");
header("Content-Type: text/plain");
die("Can not connect to the database. Please try again later.");
}
Once you have the PDO
object, you can use it to
query the database.
$rows = $db->query("SQL query string"); # fill in the query string
$rows = $db->query("SELECT * FROM Potluck;");
foreach($rows as $row){
print_r($row) . "\n";
}
PDO object's query function returns a PDOStatement object that contains the rows that match a query
Array ([id] => 1 [0] => 1 ...)
Array ([id] => 2 [0] => 2 ...)
Each row from the output is an associative array both with the column names AND positional indices as the default.
Array ( [id] => 1 [0] => 1
[name] => Lauren [1] => Lauren
[dish] => Paleo Apple Tart [2] => Paleo Apple Tart
[serves] => 8 [3] => 8
[temperature] => cold [4] => cold)
Array ( [id] => 2 [0] => 2
[name] => Stephen [1] => Stephen
[dish] => Balsamic Brussels Sprouts
[2] => Balsamic Brussels Sprouts
[serves] => 8 [3] => 8
[temperature] => hot [4] => hot )
Example: in your PHP code $row["dish"] or $row[2] gives the contents of the dish column.
$db = new PDO($ds, $user, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$rows = $db->query("SELECT * FROM Potluck;");
# kaboom!
Using setAttribute
, you can tell PDO to throw (generate) a
PDOException
when an error occurs.
The exceptions will appear as error messages on the page output.
You can catch the exception to gracefully handle the error.
fetch
The query
returns a PDOStatement
To get the data out of the rows you either use a foreach
loop OR
you can fetchAll
to get all information from the statement
(fetch
will only get one row, whatever is "next" in the PDO object)
PDO::FETCH_BOTH
is the default fetch style, but there are others
$db = new PDO($ds, $user, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$rows = $db->query("SELECT * FROM Potluck LIMIT 1;");
$row = $rows->fetch(PDO::FETCH_ASSOC);
print_r($row); # Just get the first row
Array ( [id] => 1
[name] => Lauren
[dish] => Paleo Apple Tart
[serves] => 8
[temperature] => cold)