Unit 5 PHP
Unit 5 PHP
What is MySQL?
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
Note: In the PDO example above we have also specified a database (myDB). PDO require a valid
database to connect to. If no database is specified, an exception is thrown.
MySQLi Object-Oriented:
$conn->close();
MySQLi Procedural:
mysqli_close($conn);
PDO:
$conn = null;
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
Note: When you create a new database, you must only specify the first three arguments to the
mysqli object (servername, username and password).
Tip: If you have to use a specific port, add an empty string for the database-name argument, like this:
new mysqli("localhost", "username", "password", "", port)
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
We will create a table named "MyGuests", with five columns: "id", "firstname", "lastname", "email"
and "reg_date":
The data type specifies what type of data the column can hold.
After the data type, you can specify other optional attributes for each column:
NOT NULL - Each row must contain a value for that column, null values are not
allowed
DEFAULT value - Set a default value that is added when no other value is passed
UNSIGNED - Used for number types, limits the stored data to positive numbers and
zero
AUTO INCREMENT - MySQL automatically increases the value of the field by 1 each
time a new record is added
PRIMARY KEY - Used to uniquely identify the rows in a table. The column with
PRIMARY KEY setting is often an ID number, and is often used with
AUTO_INCREMENT
Each table should have a primary key column (in this case: the "id" column). Its value must
be unique for each record in the table.
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->close();
?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn = null;
?>
The INSERT INTO statement is used to add new records to a MySQL table:
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
Example (PDO)
Update Data
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
Delete Data
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
First, we set up an SQL query that selects the id, firstname and lastname
columns from the MyGuests table. The next line of code runs the query and
puts the resulting data into a variable called $result.
Then, the function num_rows() checks if there are more than zero rows
returned.
If there are more than zero rows returned, the function fetch_assoc() puts
all the results into an associative array that we can loop through.
The while() loop loops through the result set and outputs the data from the
id, firstname and lastname columns.
function current() {
return "<td style='width:150px;border:1px solid black;'>" .
parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname",
$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM
MyGuests");
$stmt->execute();