0% found this document useful (0 votes)
124 views

Chapter 4-Connecting To Databases

This document discusses connecting PHP to MySQL databases. It explains that MySQL is an open-source database system that is commonly used with PHP. It then describes three ways to connect PHP to MySQL - using MySQLi extension, PDO, or a procedural MySQLi approach. The document provides code examples for connecting to a MySQL database, creating a database and table, and inserting and selecting data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
124 views

Chapter 4-Connecting To Databases

This document discusses connecting PHP to MySQL databases. It explains that MySQL is an open-source database system that is commonly used with PHP. It then describes three ways to connect PHP to MySQL - using MySQLi extension, PDO, or a procedural MySQLi approach. The document provides code examples for connecting to a MySQL database, creating a database and table, and inserting and selecting data.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Chapter 4: Connecting to Databases

What is MySQL? 

MySQL is an open-source relational database management system (RDBMS). It is the most


popular database system used with PHP. MySQL is developed, distributed, and supported by
Oracle Corporation.  
 The data in a MySQL database are stored in tables which consists of columns and rows.
 MySQL is a database system that runs on a server.
 MySQL is ideal for both small and large applications.
 MySQL is very fast, reliable, and easy to use database system. It uses standard SQL
 MySQL compiles on a number of platforms.

How to connect PHP with MySQL Database? 


PHP 5 and later can work with a MySQL database using:  
1. MySQLi extension.
2. PDO (PHP Data Objects).
Difference Between MySQLi and PDO  
 PDO works on 12 different database systems, whereas MySQLi works only with
MySQL databases.
 Both PDO and MySQLi are object-oriented, but MySQLi also offers a procedural
API.
 If at some point of development phase, the user or the development team wants to
change the database then it is easy to that in PDO than MySQLi as PDO supports 12
different database systems. He would have to only change the connection string and
a few queries. With MySQLi, he will need to rewrite the entire code including the
queries.
There are three ways of working with MySQL and PHP 
1. MySQLi (object-oriented)
2. MySQLi (procedural)
3. PDO

Connecting to MySQL database using PHP

The mysqli_connect() function attempts to open a connection to the MySQL Server running


on host which can be either a host name or an IP address. Passing the NULL value or the string
"localhost" to this parameter, the local host is assumed. When possible, pipes will be used
instead of the TCP/IP protocol. If successful, the mysqli_connect() will return an object
representing the connection to the database, or FALSE on failure.

The username and password parameters specify the username and password under which to


connect to the MySQL server. If the password is not provided (the NULL value is passed), the
MySQL server will attempt to authenticate the user against those user records which have no
password only. This allows one username to be used with different permissions (depending on if
a password as provided or not).
The dbname parameter if provided will specify the default database to be used when performing
queries.

The port and socket parameters are used in conjunction with the host parameter to further control


how to connect to the database server. The port parameter specifies the port number to attempt to
connect to the MySQL server on, while the socket parameter specifies the socket or named pipe
that should be used.

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

Host Optional. Specifies a host name or an IP address

username Optional. Specifies the MySQL username

Password Optional. Specifies the MySQL password

Dbname Optional. Specifies the default database to be used

Port Optional. Specifies the port number to attempt to connect to the


MySQL server

Socket Optional. Specifies the socket or named pipe to be used

 Using MySQLi procedural procedure :We will see a procedural approach of MySQLi to


establish a connection to MySQL database from a PHP script as described below. 

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.

Using MySQLi procedural procedure 


Syntax 
mysqli_close($conn);

Database Queries

A query is a question or a request. We can query a database for specific information and have a
recordset returned.

Look at the following query (using standard SQL):

SELECT LastName FROM Employees

The query above selects all the data in the "LastName" column from the "Employees" table.

Connect to an existing Database


PHP Connect to MySQL

PHP 5 and later can work with a MySQL database using:

 MySQLi extension (the "i" stands for improved)


 PDO (PHP Data Objects)

Open a Connection to MySQL

Before we can access data in the MySQL database, we need to be able to connect to the server:

Example (MySQLi Procedural)


<?php
$servername = "localhost";
$username = "root";
$password = "";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>

Close the Connection

The connection will be closed automatically when the script ends. To close the connection
before, use the following:

MySQLi Procedural:
mysqli_close($conn);

PHP Create a MySQL Database

A database consists of one or more tables.You will need special CREATE privileges to create or
to delete a MySQL database.

Create a MySQL Database Using MySQLi


Procedural style:
mysqli_query(connection, query, resultmode)
Parameter Values
Parameter Description

connection Required. Specifies the MySQL connection to use

Query Required. Specifies the SQL query string

resultmode Optional. A constant. Can be one of the following:

 MYSQLI_USE_RESULT (Use this to retrieve large amount of


data)
 MYSQLI_STORE_RESULT (This is default)

Return For successful SELECT, SHOW, DESCRIBE, or EXPLAIN queries it


Value: will return a mysqli_result object. For other successful queries it
will return TRUE. FALSE on failure

PHP 5+
Version:

The CREATE DATABASE statement is used to create a database in MySQL.

The following examples create a database named "aip":

<?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);
?>

PHP MySQL Create Table


A database table has its own unique name and consists of columns and rows.
Create a MySQL Table Using MySQLi

The CREATE TABLE statement is used to create a table in MySQL.

We will create a table named "MyGuests", with five columns: "id", "firstname", "lastname",
"email" and "reg_date":

Example (MySQLi Procedural)


<?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());
}

// sql to create table


$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)";

if (mysqli_query($conn, $sql)) {
  echo "Table MyGuests created successfully";
} else {
  echo "Error creating table: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

PHP MySQL Insert Data


Insert Data Into MySQL Using MySQLi .After a database and a table have been created, we can
start adding data in them.

Here are some syntax rules to follow:

 The SQL query must be quoted in PHP


 String values inside the SQL query must be quoted
 Numeric values must not be quoted
 The word NULL must not be quoted

The INSERT INTO statement is used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)
Note: If a column is AUTO_INCREMENT (like the "id" column) or TIMESTAMP with default
update of current_timesamp (like the "reg_date" column), it is no need to be specified in the SQL
query; MySQL will automatically add the value.
Example (MySQLi Procedural)
<?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());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', '[email protected]')";

if (mysqli_query($conn, $sql)) {
  echo "New record created successfully";
} else {
  echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

Retrieve Data from a Database


Select Data from a MySQL Database.

The SELECT statement is used to select data from one or more tables:

SELECT column_name(s) FROM table_name

or we can use the * character to select ALL columns from a table:

SELECT * FROM table_name

Select Data With MySQLi

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());
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";


$result = mysqli_query($conn, $sql);

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 syntax


mysqli_num_rows(mysqli_result $result): int|string
Note:
If the number of rows is greater than PHP_INT_MAX, the number will be returned
as a string.

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.

SELECT column_name(s) FROM table_name WHERE column_name operator value 

Select and Filter Data with MySQLi

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:

Example (MySQLi Procedural)


<?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());
}

$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE lastname='Doe'";


$result = mysqli_query($conn, $sql);

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);
?>

Modify Existing Data


Update Data in a MySQL Table Using MySQLi.

The UPDATE statement is used to update existing records in a table:

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!

Let's look at the "MyGuests" table:

id Firstname Lastname email reg_date

1 John Doe [email protected] 2014-10-22 14:26:15

2 Mary Moe [email protected] 2014-10-23 10:22:30

Example (MySQLi Procedural)


<?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());
}

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

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:

id Firstname Lastname Email reg_date

1 John Doe [email protected] 2014-10-22 14:26:15

2 Mary Doe [email protected] 2014-10-23 10:22:30

Remove Existing Data


Delete Data from a MySQL Table Using MySQLi

The DELETE statement is used to delete records from a table:

DELETE FROM table_name


WHERE some_column = some_value
Notice the WHERE clause in the DELETE syntax: The WHERE clause specifies which
record or records that should be deleted. If you omit the WHERE clause, all records will be
deleted!
<?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());
}

// sql to delete a record


$sql = "DELETE FROM MyGuests WHERE id=3";

if (mysqli_query($conn, $sql)) {
  echo "Record deleted successfully";
} else {
  echo "Error deleting record: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

Limit Data Selections From a MySQL Database

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:

$sql = "SELECT * FROM Orders LIMIT 30";

When the SQL query above is run, it will return the first 30 records.

What if we want to select records 16 - 25 (inclusive)?

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)":

$sql = "SELECT * FROM Orders LIMIT 10 OFFSET 15";


You could also use a shorter syntax to achieve the same result:

$sql = "SELECT * FROM Orders LIMIT 15, 10";

Notice that the numbers are reversed when you use a comma.

Prepared Statements

The MySQL database supports prepared statements. A prepared statement or a parameterized


statement is used to execute the same statement repeatedly with high efficiency and protect
against SQL injections.

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.

The MySQL server supports using anonymous, positional placeholder with ?.

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 (?, ?, ?)";

if($stmt = mysqli_prepare($conn, $sql))


{
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "sss", $first_name, $last_name, $email);
/* Set the parameters values and execute the statement again to insert another
row */
$first_name = "Hermione";
$last_name = "Granger";
$email = "[email protected]";
mysqli_stmt_execute($stmt);
/* Set the parameters values and execute the statement to insert a row */
$first_name = "Ron";
$last_name = "Weasley";
$email = "[email protected]";
mysqli_stmt_execute($stmt);
echo "Records inserted successfully.";
}
 else
{
echo "ERROR: Could not prepare query: $sql. " . mysqli_error($conn);
}
// Close statement
mysqli_stmt_close($stmt); // Close connection
mysqli_close($conn);
?>

Database security using server-side Scripting

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.

Encrypted Storage Model

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.

You can use also


random_bytes — Generates cryptographically secure pseudo-random bytes
random_bytes(int $length): string

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.

PHP password_verify Function


PHP password_verify Function is used to check the hashed password and verify it is matching
with an original password or not.
Syntax:
password_verify(string $password, string $hash)

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

PHP store password in the database


When the user registers or sign up in your application, you can hash the entered password with
one of the above password_hash() function and store the hashed password in the database.
Here, we have used the PASSWORD_BCRYPT hashing algorithm to hash the password and
then use the mysqli database connection code to connect to the database and insert query to insert
in the 'users' table. Please make sure to replace the database credentials with yours.
$username = $_POST['username'];
$password = $_POST['password'];
$hash = password_hash($password, PASSWORD_BCRYPT);
$conn = new mysqli('localhost', 'root', '', 'aip');
//Check for connection error
if($conn->connect_error){
die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error);
}
$insert = "INSERT INTO `user` (`uid`, `username`, `password`) VALUES
(NULL, $username, $hash)";
if($conn->query($insert)){
echo 'Data inserted successfully';
}
else{
echo 'Error '.$conn->error;
}

Match the user's password with hash password


When a user attempts to login in your application, we have used the password_verify() function
to match the provided password with the stored hash password value.
$username = $_POST['username'];
$password = $_POST['password'];
$conn = new mysqli('localhost', 'root', '', 'aip');
if($conn->connect_error){
die("Error in DB connection: ".$conn->connect_errno." : ".$conn->connect_error);
}
$select = "SELECT password FROM `user` WHERE username = '$username'";
$result = $conn->query($select);
while($row = $result->fetch_object()){
$hash = $row->password;
}
if(password_verify($password, $hash)) {
print "Login succeeds";
} else {
print "Login fails.";
}

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/

You might also like