Chapter 4-Connecting To Databases
Chapter 4-Connecting To Databases
What is MySQL?
Specifying the socket parameter will not explicitly determine the type of connection to be used
when connecting to the MySQL server. How the connection is made to the MySQL database is
determined by the host parameter.
Syntax
mysqli_connect(host, username, password, dbname, port, socket)
Parameter Description
Syntax:
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Creating connection
$conn = mysqli_connect($servername, $username, $password);
// Checking connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Output:
Explanation: In MySQLi procedural approach instead of creating an instance we can use the
mysqli_connect() function available in PHP to establish a connection. This function takes the
information as arguments such as host, username, password, database name etc. This function
returns MySQL link identifier on successful connection or FALSE when failed to establish a
connection.
Closing A Connection
When we establish a connection to MySQL database from a PHP script, we should also
disconnect or close the connection when our work is finished. Here we have described the
syntax of closing the connection to a MySQL database. We have assumed that the reference to
the connection is stored in $conn variable.
Database Queries
A query is a question or a request. We can query a database for specific information and have a
recordset returned.
SELECT LastName FROM Employees
The query above selects all the data in the "LastName" column from the "Employees" table.
Before we can access data in the MySQL database, we need to be able to connect to the server:
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
The connection will be closed automatically when the script ends. To close the connection
before, use the following:
MySQLi Procedural:
mysqli_close($conn);
A database consists of one or more tables.You will need special CREATE privileges to create or
to delete a MySQL database.
PHP 5+
Version:
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE aip";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
We will create a table named "MyGuests", with five columns: "id", "firstname", "lastname",
"email" and "reg_date":
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
The INSERT INTO statement is used to add new records to a MySQL table:
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
The SELECT statement is used to select data from one or more tables:
The following example selects the id, firstname and lastname columns from the MyGuests table
and displays it on the page:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "aip";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Procedural style
mysqli_fetch_assoc(mysqli_result $result): array|null|false
Fetches one row of data from the result set and returns it as an associative array. Each subsequent
call to this function will return the next row within the result set, or null if there are no more
rows.
Select and Filter Data from a MySQL Database
The WHERE clause is used to filter records. The WHERE clause is used to extract only those
records that fulfill a specified condition.
The following example selects the id, firstname and lastname columns from the MyGuests table
where the lastname is "Doe", and displays it on the page:
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Notice the WHERE clause in the UPDATE syntax: The WHERE clause specifies which
record or records that should be updated. If you omit the WHERE clause, all records will be
updated!
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
After the record is updated, the table will look like this:
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
MySQL provides a LIMIT clause that is used to specify the number of records to return.The
LIMIT clause makes it easy to code multi page results or pagination with SQL, and is very useful
on large tables. Returning a large number of records can impact on performance.
Assume we wish to select all records from 1 - 30 (inclusive) from a table called "Orders". The
SQL query would then look like this:
When the SQL query above is run, it will return the first 30 records.
Mysql also provides a way to handle this: by using OFFSET. The SQL query below says "return
only 10 records, start on record 16 (OFFSET 15)":
Notice that the numbers are reversed when you use a comma.
Prepared Statements
Basic workflow
The prepared statement execution consists of two stages: prepare and execute. At the prepare
stage a statement template is sent to the database server. The server performs a syntax check and
initializes server internal resources for later use.
Prepare is followed by execute. During execute the client binds parameter values and sends them
to the server. The server executes the statement with the bound values using the previously
created internal resources.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL server with
default setting (user 'root' with no password) */
$conn = mysqli_connect("localhost", "root", "", "aip");
// Check connection
if($conn === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Prepare an insert statement
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)";
Database security refers to the various measures organizations take to ensure their databases are
protected from internal and external threats. Database security includes protecting the database
itself, the data it contains, its database management system, and the various applications that
access it. Organizations must secure databases from deliberate attacks such as cyber security
threats, as well as the misuse of data and databases from those who can access them.
In the last several years, the number of data breaches has risen considerably. In addition to the
considerable damage these threats pose to a company’s reputation and customer base, there are
an increasing number of regulations and penalties for data breaches that organizations must deal
with, such as those in the General Data Protection Regulation (GDPR)—some of which are
extremely costly. Effective database security is key for remaining compliant, protecting
organizations’ reputations, and keeping their customers.
Designing Databases
The first step is always to create the database, unless you want to use one from a third party.
When a database is created, it is assigned to an owner, who executed the creation statement.
Usually, only the owner (or a superuser) can do anything with the objects in that database, and in
order to allow other users to use it, privileges must be granted.
Connecting to Database
You may want to establish the connections over SSL to encrypt client/server communications for
increased security, or you can use SSH to encrypt the network connection between clients and
the database server. If either of these is used, then monitoring your traffic and gaining
information about your database will be difficult for a would-be attacker.
SSL/SSH protects data travelling from the client to the server: SSL/SSH does not protect
persistent data stored in a database. SSL is an on-the-wire protocol.
Once an attacker gains access to your database directly (bypassing the webserver), stored
sensitive data may be exposed or misused, unless the information is protected by the database
itself. Encrypting the data is a good way to mitigate this threat, but very few databases offer this
type of data encryption.
The easiest way to work around this problem is to first create your own encryption package, and
then use it from within your PHP scripts. PHP can assist you in this with several extensions, such
as OpenSSL and Sodium, covering a wide variety of encryption algorithms. The script encrypts
the data before inserting it into the database, and decrypts it when retrieving.
Hashing
A hash is designed to act as a “one-way function”: A mathematical operation that’s easy to
perform, but very difficult to reverse. Like other forms of encryption, it turns readable data into a
scrambled cipher. But instead of allowing someone to decrypt that data with a specific key, as
typical encryption functions do, hashes aren’t designed to be decrypted. Instead, when you enter
your password on a website, it simply performs the same hash again and checks the results
against the hash it created of your password when you chose it, verifying the password’s validity
without having to store the sensitive password itself.
https://www.wired.com/2016/06/hacker-lexicon-password-hashing/
In the case of truly hidden data, if its raw representation is not needed (i.e. will not be displayed),
hashing should be taken into consideration. The well-known example for hashing is storing the
cryptographic hash of a password in a database, instead of the password itself.
The password functions provide a convenient way to hash sensitive data and work with these
hashes.
Hash Algorithms such as md5(), sha1(), and hash() Functions have major drawbacks of the
method was that these algorithms were very fast due to less complexity and thus more
vulnerable to attacks, they are even suggested not to use in a full-fledged project of greater
importance. These methods are old and not very secure as this can be easily cracked. In the
latest versions of PHP, there is no need to encrypt or decrypt a password or use your own
hashing algorithm. Thus, PHP now provides with a couple new methods to hash user
passwords in a much more optimized and secure way.
password_hash() is used to hash a given string using the strongest algorithm currently available
and password_verify() checks whether the given password matches the hash stored in database.
password_hash() Function
Here is what the PHP documentation says about password_hash :
password_hash() creates a new password hash using a strong one-way hashing algorithm.
password_hash() is compatible with crypt().
Syntax:
string password_hash($string, $algo, $options)
Parameters: The function an take up to a maximum of three parameters as follows:
$string: This parameter expects the string to be hashed.
$algo: This parameter expects an integer value that refers to the algorithm to be
used for the purpose. Three algorithms are available as follows:
PASSWORD_DEFAULT: This is the recommended algo, as the
developer team of PHP are adding new algorithms and updating the
following to be the best option.
PASSWORD_BCRYPT: This algorithm uses the CRYPT_BLOWFISH
algorithm and generates a crypt() equivalent hash.
PASSWORD_ARGON2I: Uses the Argon2 Hashing Algorithm.
$options: This is an optional parameter that expects an array of advanced options as
described. The supported options for each algorithm slightly differs from each
other. The supported options are as follows:
Supported options for PASSWORD_BCRYPT:
Cost: Maximum Algorithmic Cost to be applied. Default value is 10.
Algorithmic cost directly affects the loading time and depends
significally on the hardware running.
Salt: Developers can provide manual salts as well, but it is not
recommended.
mcrypt_create_iv — Creates an initialization vector (IV) from a random source
Syntax
mcrypt_create_iv(int $size, int $source = MCRYPT_DEV_URANDOM): string
size
The size of the IV.
source
The source of the IV. The source can be MCRYPT_RAND (system random number
generator), MCRYPT_DEV_RANDOM (read data from /dev/random)
and MCRYPT_DEV_URANDOM (read data from /dev/urandom). Prior to
5.3.0, MCRYPT_RAND was the only one supported on Windows.
Generates an arbitrary length string of cryptographic random bytes that are suitable for
cryptographic use, such as when generating salts, keys or initialization vectors.
$options = array(
'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
'cost' => 12,
);
$password_hash = password_hash($password, PASSWORD_BCRYPT, $options);
Supported options for PASSWORD_ARGON2I:
Memory cost: Maximum Memory Cost to be applied to generate the
hash.
Time cost: Maximum Time to be taken to calculate the hash.
Threads: Number of threads to be used.
Return Type: This function returns the hashed string on success or FALSE.
$options = [
'memory_cost' => 2048
'time_cost' => 4,
'threads' => 3,
];
$password_hash = password_hash($password, PASSWORD_ARGON2I, $options);
In cryptography, a salt is random data that is used as an additional input to a one-way function
that hashes data, a password or passphrase. Salts are used to safeguard passwords in storage.
Historically, only a cryptographic hash function of the password was stored on a system, but
over time, additional safeguards were developed to protect against duplicate or common
passwords being identifiable (as their hashes are identical). Salting is one such protection.
Password verify takes only 2 parameters, one is input password by a user and hashed password
from DB.
PHP password_hash and password_verify Example
<?php
$password = 123;
echo $hashed_password = password_hash($password, PASSWORD_DEFAULT);
if(password_verify($password, $hashed_password)) {
// If the password inputs matched the hashed password in the database
echo "Password verified";
}
Output:
$2y$10$dh8ntY.BhgCarjZuEwG70.vFLt4Af6vz08Ibd9TsMRv/4PegCJToS
Password verified
References
https://www.geeksforgeeks.org/php-mysql-database-introduction/
https://www.sumologic.com/blog/what-is-database-security/
https://www.geeksforgeeks.org/php-md5-sha1-hash-functions/
https://www.phptutorial.net/php-tutorial/php-password_hash/
https://www.etutorialspoint.com/index.php/185-php-secure-password-hash-and-password-verify
https://www.php.net/manual/en/