HW 6 Introduction
Database manipulation (create/insert)
Accessing SQL from PHP
HTML: Webpage content
CSS: Webpage presentation
JavaScript: Webpage functionality (client-side)
AJAX: Fetching data from the internet
Regular Expressions: Validating input
SQL: Storing data
A Full stack website consists of three layers.
Note: full instructions will be in tomorrows lab.
mysql-ctl start
to start the MySQL servermysql-ctl cli
to begin entering SQL commandsEach 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)
);
Data types are listed here.
SHOW TABLES;
displays a list of the tables
DESCRIBE table_name;
display the columns of the table
DROP TABLE table_name;
deletes a table
INSERT
INSERT is used to insert a new record into an existing table.
Syntax:
INSERT INTO TABLE_NAME (column1, column2,...columnN)
VALUES (value1,value2,...valueN);
Example:
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00);
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'Khilan', 25, 'Delhi', 1500.00);
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'kaushik', 23, 'Kota', 2000.00);
$name = new PDO("mysql:dbname=database;host=server;charset=utf8", username, password);
$name->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$name->query("SQL query");
$db = new PDO("mysql:dbname=world;host=localhost;charset=utf8", "root", "");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->query("SELECT * FROM countries WHERE population > 100000000;");
PDO object's query function returns rows that match a query
$db = new PDO("mysql:dbname=world;host=localhost;charset=utf8", "root", "");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$rows = $db->query("SQL query");
foreach ($rows as $row) {
do something with $row;
}
query returns all result rows
$count = $db->exec("INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00);");
exec
runs the given SQL code and returns the number of rows affected.
# get query parameter for name of movie
$title = $_GET["movietitle"];
$rows = $db->query("SELECT year FROM movies WHERE name = '$title'");
NOTE: THIS CODE IS NOT SECURE!
We will discuss security and how to make this code safe later in the quarter.