Create A Mysql Database Using Mysqli and Pdo
Create A Mysql Database Using Mysqli and Pdo
Create A Mysql Database Using Mysqli and Pdo
What is MySQL?
The data in a MySQL database are stored in tables. A table is a collection of related data, and
it consists of columns and rows.
<?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();
?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $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. For a
complete reference of all the available data types, go to our Data Types
reference.
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.
MYSQL-i
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 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;
?>
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a
related column between them.
SELECT column_name(s)
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name;
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
SELECT column_name(s)
FROM table1
RIGHT JOIN table2 ON table1.column_name = table2.column_name;
1) COUNT
2) SUM
3) AVG
4) MIN
5) MAX
For instance, from our myflix database , management may require following
reports
COUNT (*) is a special implementation of the COUNT function that returns the
count of all the rows in a specified table. COUNT (*) also considers Nulls and
duplicates.
11 20-06-2012 NULL 1 1 0
12 22-06-2012 25-06-2012 1 2 0
13 22-06-2012 25-06-2012 3 2 0
14 21-06-2012 24-06-2012 2 2 0
15 23-06-2012 NULL 3 3 0
Let's suppose that we want to get the number of times that the movie with id 2
has been rented out
Executing the above query in MySQL workbench against myflixdb gives us the
following results.
COUNT('movie_id')
3
DISTINCT Keyword
The DISTINCT keyword that allows us to omit duplicates from our results. This is
achieved by grouping similar values together .
Now let's execute the same query with the distinct keyword -
movie_id
MIN function
The MIN function returns the smallest value in the specified table field.
As an example, let's suppose we want to know the year in which the oldest movie
in our library was released, we can use MySQL's MIN function to get the desired
information.
Executing the above query in MySQL workbench against myflixdb gives us the
following results.
MIN('year_released')
2005
MAX function
Just as the name suggests, the MAX function is the opposite of the MIN function.
It returns the largest value from the specified table field.
Let's assume we want to get the year that the latest movie in our database was
released. We can easily use the MAX function to achieve that.
Executing the above query in MySQL workbench using myflixdb gives us the
following results.
MAX('year_released')
2012
SUM function
Suppose we want a report that gives total amount of payments made so far. We
can use the MySQL SUM function which returns the sum of all the values in
the specified column. SUM works on numeric fields only. Null values are
excluded from the result returned.
payment_ membership_ payment_ description amount_ external_ reference
id number date paid _number
The query shown below gets the all payments made and sums them up to return
a single result.
Executing the above query in MySQL workbench against the myflixdb gives the
following results.
SUM('amount_paid')
10500
AVG function
MySQL AVG function returns the average of the values in a specified
column. Just like the SUM function, it works only on numeric data types.
Suppose we want to find the average amount paid. We can use the following
query -
Executing the above query in MySQL workbench, gives us the following results.
AVG('amount_paid')
3500
Summary
MySQL supports all the five (5) ISO standard aggregate functions COUNT,
SUM, AVG, MIN and MAX.
SUM and AVG functions only work on numeric data.
If you want to exclude duplicate values from the aggregate function results,
use the DISTINCT keyword. The ALL keyword includes even duplicates. If
nothing is specified the ALL is assumed as the default.
Aggregate functions can be used in conjunction with other SQL clauses
such as GROUP BY
Let’s consider a simple web application with a login form. The code for the HTML
form is shown below.
</form>
HERE,
The above form accepts the email address, and password then submits
them to aPHP file named index.php.
It has an option of storing the login session in a cookie. We have deduced
this from the remember_me checkbox. It uses the post method to submit
data. This means the values are not displayed in the URL.
Let’s suppose the statement at the backend for checking user ID is as follows
HERE,
The above statement uses the values of the $_POST[] array directly
without sanitizing them.
The password is encrypted using MD5 algorithm.
Step 4) Click Run SQL. You will see the following result
The above code can be exploited by commenting out the password part and
appending a condition that will always be true. Let’s suppose an attacker
provides the following input in the email address field.
[email protected]' OR 1 = 1 LIMIT 1 -- ' ]
HERE,
[email protected] ends with a single quote which completes the string quote
OR 1 = 1 LIMIT 1 is a condition that will always be true and limits the
returned results to only one record.
-- ' AND … is a SQL comment that eliminates the password part.
Copy the above SQL statement and paste it in SQL FiddleRun SQL Text box as
shown below
To get round that, we can instead exploit the password field. The diagram below
shows the steps that you must follow
HERE,
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$firstname = "Mary";
$lastname = "Moe";
$email = "[email protected]";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "[email protected]";
$stmt->execute();
$stmt->close();
$conn->close();
?>
This function binds the parameters to the SQL query and tells the database
what the parameters are. The "sss" argument lists the types of data that the
parameters are. The s character tells mysql that the parameter is a string.
i - integer
d - double
s - string
b - BLOB
// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "[email protected]";
$stmt->execute();