Uploaded by joshua.kalani137

PHP Mysql Tutorial 1

advertisement
PHP /MySQL Application Development
#SECTION 1
Ways of Connecting to MySQL through PHP
In order to store or access the data inside a MySQL database, you first need to connect to the MySQL
database server. PHP offers two different ways to connect to MySQL server: MySQLi (Improved MySQL)
and PDO (PHP Data Objects) extensions.
While the PDO extension is more portable and supports more than twelve different databases, MySQLi
extension as the name suggests supports MySQL database only. MySQLi extension however provides an
easier way to connect to, and execute queries on, a MySQL database server. Both PDO and MySQLi
offer an object-oriented API, but MySQLi also offers a procedural API which is relatively easy for
beginners to understand.
Connecting to MySQL Database Server
In PHP you can easily do this using the mysqli_connect() function. All communication between PHP and
the MySQL database server takes place through this connection. Here're the basic syntaxes for
connecting to MySQL using MySQLi and PDO extensions:
Syntax: MySQLi, Procedural way
$link = mysqli_connect("hostname", "username", "password", "database");
Syntax: MySQLi, Object Oriented way
$mysqli = new mysqli("hostname", "username", "password", "database");
Syntax: PHP Data Objects (PDO) way
$pdo = new PDO("mysql:host=hostname;dbname=database", "username", "password");
 “$link” is the database connection resource variable.
 “mysqli_connect(…)” is the function for php database connection
 “$hostname” is the name or IP address of the server hosting MySQL server.
 “$username” is a valid user name in MySQL server.
 “$password” is a valid password associated with a user name in MySQL server.
 “$database” is a valid database name in MySQL server.
The hostname parameter in the above syntax specify the host name (e.g. localhost), or IP address of the
MySQL server, whereas the username and password parameters specifies the credentials to access
MySQL server, and the database parameter, if provided will specify the default MySQL database to be
used when performing queries.
The following example shows how to connect to MySQL database server using MySQLi (both procedural
and object oriented way) and PDO extension.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Print host information
echo "Connect Successfully. Host info: " . mysqli_get_host_info($link);
?>
Closing the MySQL Database Server Connection
The connection to the MySQL database server will be closed automatically as soon as the execution of
the script ends. However, if you want to close it earlier you can do this by simply calling the PHP
mysqli_close() function.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Print host information
echo "Connect Successfully. Host info: " . mysqli_get_host_info($link);
// Close connection
mysqli_close($link);
?>
NB: Anytime the application needs to interact with the database, a connection has to be set first to the
database server.
Creating MySQL Database Using PHP
Before saving or accessing the data, we need to create a database first. The CREATE DATABASE
statement is used to create a new database in MySQL.
Let's make a SQL query using the CREATE DATABASE statement, after that we will execute this SQL
query through passing it to the PHP mysqli_query() function to finally create our database. The following
example creates a database named demo.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt create database query execution
$sql = "CREATE DATABASE demo";
if(mysqli_query($link, $sql)){
echo "Database created successfully";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
Creating Tables inside MySQL Database Using PHP
In the previous section we’ve learned how to create a database on MySQL server. Now it's time to create
some tables inside the database that will actually hold the data. A table organizes the information into
rows and columns.
The SQL CREATE TABLE statement is used to create a table in database.
Let's make a SQL query using the CREATE TABLE statement, after that we will execute this SQL query
through passing it to the PHP mysqli_query() function to finally create our table.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password)
The link connection object has been modified to access the specified database
demo created using the above script
*/
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt create table query execution
$sql = "CREATE TABLE persons(
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(30) NOT NULL,
last_name VARCHAR(30) NOT NULL,
email VARCHAR(70) NOT NULL UNIQUE
)";
if(mysqli_query($link, $sql)){
echo "Table created successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
The PHP code in the above example creates a table named persons with four columns id, first_name,
last_name and email inside the demo database.
Notice that each field name is followed by a data type declaration; this declaration specifies what type of
data the column can hold, whether integer, string, date, etc.
There are a few additional constraints (also called modifiers) that are specified after the column name in
the preceding SQL statement, like NOT NULL, PRIMARY KEY, AUTO_INCREMENT, etc. Constraints
define rules regarding the values allowed in columns.
Please refer to MySQL database tutorial attached in the resources folder in piazza.
Inserting Data into a MySQL Database Table
Now that you've understood how to create database and tables in MySQL, in this section you will learn
how to execute SQL query to insert records into a table.
The INSERT INTO statement is used to insert new rows in a database table.
Let's make a SQL query using the INSERT INTO statement with appropriate values, after that we will
execute this insert query through passing it to the PHP mysqli_query() function to insert data in table.
Here's an example, which insert a new row to the persons table by specifying values for the first_name,
last_name and email fields.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES ('Peter',
'Parker', 'peterparker@mail.com')";
if(mysqli_query($link, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
Inserting Multiple Rows into a Table
You can also insert multiple rows into a table with a single insert query at once. To do this, include
multiple lists of column values within the INSERT INTO statement, where column values for each row
must be enclosed within parentheses and separated by a comma.
Let's insert few more rows into the persons table, like this:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES
('John', 'Rambo', 'johnrambo@mail.com'),
('Clark', 'Kent', 'clarkkent@mail.com'),
('John', 'Carter', 'johncarter@mail.com'),
('Harry', 'Potter', 'harrypotter@mail.com')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
Insert Data into a Database from an HTML Form
In the previous section, we have learned how to insert data into database from a PHP script. Now, we'll
see how we can insert data into database obtained from an HTML form. Let's create an HTML form that
can be used to insert new records to persons table.
Step 1: Creating the HTML Form
Here's a simple HTML form that has three text <input> fields and a submit button.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Record Form</title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="firstName">First Name:</label>
<input type="text" name="first_name" id="firstName">
</p>
<p>
<label for="lastName">Last Name:</label>
<input type="text" name="last_name" id="lastName">
</p>
<p>
<label for="emailAddress">Email Address:</label>
<input type="text" name="email" id="emailAddress">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
Step 2: Retrieving and Inserting the Form Data
When a user clicks the submit button of the add record HTML form, in the example above, the form data
is sent to 'insert.php' file. The 'insert.php' file connects to the MySQL database server, retrieves forms
fields using the PHP $_REQUEST variables and finally execute the insert query to ad d the records.
Here is the complete code of our 'insert.php' file:
NB: You can also get form data values using $_POST or $_GET methods
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_REQUEST['first_name']);
$last_name = mysqli_real_escape_string($link, $_REQUEST['last_name']);
$email = mysqli_real_escape_string($link, $_REQUEST['email']);
// Attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES
('$first_name', '$last_name', '$email')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
PHP mysqli_query function
The mysqli_query function is used to execute SQL queries.
The function can be used to execute the following query types;


Insert
Select


Update
delete
It has the following syntax.
<?php
mysqli_query($link,$query) ;
?>
HERE,



―mysqli_query(…)‖ is the function that executes the SQL queries.
―$query‖ is the SQL query to be executed
―$link” is used to pass in the server connection link
Processing Inputs Received through a Web Form using prepared statement
If you remember from the previous section, we've created an HTML form to insert data into database.
Here, we're going to extend that example by implementing the prepared statement. You can use the
same HTML form to test the following insert script example, but just make sure that you're using the
correct file name in the action attribute of the form.
Here's the updated PHP code for inserting the data. If you see the example carefully you'll find we didn't
use the mysqli_real_escape_string() to escape the user inputs, like we've done in the previous section
example. Since in prepared statements, user inputs are never substituted into the query string directly, so
they do not need to be escaped correctly.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Prepare an insert statement
$sql = "INSERT INTO persons (first_name, last_name, email) VALUES (?, ?, ?)";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "sss", $first_name, $last_name, $email);
// Set parameters
$first_name = $_REQUEST['first_name'];
$last_name = $_REQUEST['last_name'];
$email = $_REQUEST['email'];
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not execute query: $sql. " . mysqli_error($link);
}
} else{
echo "ERROR: Could not prepare query: $sql. " . mysqli_error($link);
}
// Close statement
mysqli_stmt_close($stmt);
// Close connection
mysqli_close($link);
?>
Selecting Data from Database Tables
In PHP, MySQL fetches results can be obtained by the following functions. All of these functions will fetch
only one row per function call. If required, we should call such functions with a loop for getting subsequent
MySQL fetch results row by row.






mysqli_fetch_row()
mysqli_fetch_assoc()
mysqli_fetch_array()
mysqli_fetch_object()
mysqli_fetch_lengths()
mysqli_fetch_field()
mysqli_fetch_row()
This function will fetch data about the single row with which the row pointer currently exists. After fetching
the entire row details, it will be returned as an array with number indices corresponding to the MySQL
field offset.
The mysqli_fetch_row() function requires a resource data that is returned by executing query appropriate
with MySQL fetch operations. If no results found for the query, then mysqli_fetch_row() will return NULL.
Let us consider the Users table, with table data and structure is as follows.
The following PHP program is for fetching MySQL data using mysqli_fetch_row(). Before that, the
database connections are made with first two lines as usual.
<?php
$conn = mysqli_connect("localhost", "root", "test", "blog_samples") or
die("Connection Error: " . mysqli_error($conn));
$query = "SELECT * from Users";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
$row = mysqli_fetch_row($result);
print "<pre>";
print_r($row);
print "<pre>";
?>
This program will return values of the entire first row since the row pointer is at the beginning. So the
output will be as shown below that can be cross checked with the table data shown already.
<?php
Array
(
[0] =>
[1] =>
[2] =>
[3] =>
)
1
admin
admin123
student
?>
If we want to get all the row information, we should do the same process recursively by iterating through a
loop until end of the record. For example,
<?php
while($row = mysqli_fetch_row($result)) {
print "<pre>";
print_r($row);
print "<pre>";
}
?>
mysqli_fetch_assoc()
This function is similar to the mysqli_fetch_row(), except that, it will return an array of row information
containing column values are indexed with the column name. So the result type is an associative array
where each column name and values of a single row are associated together as name, value pairs.
Let us replace mysqli_fetch_row() with mysqli_fetch_assoc() in the above program which will return the
following array.
Array
(
[user_id] => 1
[user_name] => admin
[password] => admin123
[user_type] => student
)
By using this type of MySQL fetch, we can access the data by its name instead of its offset. Since,
remembering the order of fields is too tough for a huge list of columns, accessing by field name is easy
and there by this function could be preferred in such scenario.
mysqli_fetch_array()
This MySQL fetch method returns resultant array with both indices, that is, field offset and field name. So,
it would be used most probably by having both option of indexing.
Unlike above two functions, mysqli_fetch_array() accepts an optional argument for specifying resultant
array index type and its possible values are,



MYSQLI_BOTH – It is the default value that would be taken if no second argument is provided for
this function. It will provide resultant array with both indices.
MYSQLI_NUM – With this option, mysqli_fetch_array() will return array with offset indices as
same as mysqli_fetch_row().
MYSQLI_ASSOC – With this option, mysqli_fetch_array() will return array with name indices as
same as mysqli_fetch_assoc().
By replacing mysqli_fetch_row() with mysqli_fetch_array(), the output array will be,
Array
(
[0] => 1
[user_id] => 1
[1] => admin
[user_name] => admin
[2] => admin123
[password] => admin123
[3] => student
[user_type] => student
)
mysqli_fetch_object()
mysqli_fetch_object() function will return MySQL data with same structure as returned by
mysqli_fetch_assoc(), but its type is different. mysqli_fetch_object() returns object whereas
mysqli_fetch_assoc() returns array. So, the way of accessing these data will also be differed. For
example, if we are required to access user_name, after array fetch, it will be done by,
echo $row["user_name"];
Or else after object fetch, it would be,
echo $row->user_name;
mysqli_fetch_lengths()
This PHP function is used to return the string length each column value of the recently fetched row. So,
before calculating the string length, any one of the above MySQL fetch functions need to be invoked.
For example, the following program is to fetch single row data using mysqli_fetch_object() and to print the
corresponding length array to the browser.
<?php
$conn = mysqli_connect("localhost", "root", "test", "blog_samples") or
die("Connection Error: " . mysqli_error($conn));
$query = "SELECT * from Users";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
$row = mysqli_fetch_object($result);
$student_length = mysqli_fetch_lengths($result);
print "<pre>";
print_r($row);
print_r($student_length);
print "<pre>";
?>
And the output is,
stdClass Object
(
[user_id] => 1
[user_name] => admin
[password] => admin123
[user_type] => student
)
Array
(
[0] => 1
[1] => 5
[2] => 8
[3] => 7
)
Obviously, the object properties array and the length array are returned as shown above that could be
cross checked manually to ensure the property value length is correct as expected.
mysqli_fetch_field()
Unlike above functions, mysqli_fetch_field() is for getting MySQL Database table’s field information
instead of record data. And, this function also fetch one field per call and need loop implementation for
getting more fields.
These information array will be returned as an object which includes properties like, table name, field
name, field maximum length, primary key flag offset and etc. For example, the user_id field details of
Users table is returned as follows.
stdClass Object
(
[name] => user_id
[table] => Users
[def] =>
[max_length] => 1
[not_null] => 1
[primary_key] => 1
[multiple_key] => 0
[unique_key] => 0
[numeric] => 1
[blob] => 0
[type] => int
[unsigned] => 0
[zerofill] => 0
)
So far you have learnt how to create database and table as well as inserting data. Now it's time to retrieve
data what have inserted in the preceding tutorial. The SQL SELECT statement is used to select the
records from database tables. Its basic syntax is as follows:
SELECT column1_name, column2_name, columnN_name FROM table_name;
Let's make a SQL query using the SELECT statement, after that we will execute this SQL query through
passing it to the PHP mysqli_query() function to retrieve the table data.
Consider our persons database table has the following records:
+----+------------+-----------+----------------------+
| id | first_name | last_name | email
|
+----+------------+-----------+----------------------+
| 1 | Peter
| Parker
| peterparker@mail.com |
| 2 | John
| Rambo
| johnrambo@mail.com
|
| 3 | Clark
| Kent
| clarkkent@mail.com
|
| 4 | John
| Carter
| johncarter@mail.com |
| 5 | Harry
| Potter
| harrypotter@mail.com |
+----+------------+-----------+----------------------+
The PHP code in the following example selects all the data stored in the persons table (using the asterisk
character (*) in place of column name selects all the data in the table).
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM persons";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>first_name</th>";
echo "<th>last_name</th>";
echo "<th>email</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>"
echo "<td>"
echo "<td>"
echo "<td>"
echo "</tr>";
.
.
.
.
$row['id'] . "</td>";
$row['first_name'] . "</td>";
$row['last_name'] . "</td>";
$row['email'] . "</td>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
Explanation of Code (Procedural style)
In the example above, the data returned by the mysqli_query() function is stored in the $result variable.
Each time mysqli_fetch_array() is invoked, it returns the next row from the result set as an array. The
while loop is used to loops through all the rows in the result set. Finally the value of individual field can be
accessed from the row either by passing the field index or field name to the $row variable like $row['id'] or
$row[0], $row['first_name'] or $row[1], $row['last_name'] or $row[2], and $row['email'] or $row[3].
Counting Rows
Before you can go through the data in your result variable, you must know how many database rows
there are. You could, of course, just type this into your code but it is not a very good solution as the whole
script would need to be changed every time a new row was added. Instead you can use the command:
$num=mysqli_num_rows($result);
This will set the value of $num to be the number of rows stored in $result (the output you got from the
database). This can then be used in a loop to get all the data and output it on the screen
If you want to use the for loop you can obtain the loop counter value or the number of rows returned by
the query by passing the $result variable to the mysqli_num_rows() function. This loop counter value
determines how many times the loop should run.
PHP mysqli_fetch_array function
The mysqli_fetch_array function is used fetch row arrays from a query result set.
It has the following syntax.
<?php
mysqli_fetch_array($result);
?>
HERE,

“mysqli_fetch_array(…)” is the function for fetching row arrays

“$result” is the result returned by the mysqli_query function.
Filtering the Records
The WHERE clause is used to extract only those records that fulfill a specified condition.
The basic syntax of the WHERE clause can be given with:
SELECT column_name(s) FROM table_name WHERE column_name operator value
Let's make a SQL query using the WHERE clause in SELECT statement, after that we'll execute this
query through passing it to the PHP mysqli_query() function to get the filtered data.
Consider we've a persons table inside the demo database that has following records:
+----+------------+-----------+----------------------+
| id | first_name | last_name | email
|
+----+------------+-----------+----------------------+
| 1 | Peter
| Parker
| peterparker@mail.com |
| 2 | John
| Rambo
| johnrambo@mail.com
|
| 3 | Clark
| Kent
| clarkkent@mail.com
|
| 4 | John
| Carter
| johncarter@mail.com |
| 5 | Harry
| Potter
| harrypotter@mail.com |
+----+------------+-----------+----------------------+
The following PHP code selects all the rows from the persons table where first_name='john':
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM persons WHERE first_name='john'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>first_name</th>";
echo "<th>last_name</th>";
echo "<th>email</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>"
echo "<td>"
echo "<td>"
echo "<td>"
echo "</tr>";
.
.
.
.
$row['id'] . "</td>";
$row['first_name'] . "</td>";
$row['last_name'] . "</td>";
$row['email'] . "</td>";
}
echo "</table>";
// Close result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
After filtration the result set will look something like this:
+----+------------+-----------+---------------------+
| id | first_name | last_name | email
|
+----+------------+-----------+---------------------+
| 2 | John
| Rambo
| johnrambo@mail.com |
| 4 | John
| Carter
| johncarter@mail.com |
+----+------------+-----------+---------------------+
Limiting Result Sets
The LIMIT clause is used to constrain the number of rows returned by the SELECT statement. This
feature is very helpful for optimizing the page loading time as well as to enhance the readability of a
website. For example you can divide the large number of records in multiple pages using pagination,
where limited number of records will be loaded on every page from the database when a user request for
that page by clicking on pagination link.
The basic syntax of the LIMIT clause can be given with:
SELECT column_name(s) FROM table_name LIMIT row_offset, row_count;
The LIMIT clause accepts one or two parameters which must be a nonnegative integer:


When two parameters are specified, the first parameter specifies the offset of the first row to
return i.e. the starting point, whereas the second parameter specifies the number of rows to
return. The offset of the first row is 0 (not 1).
Whereas, when only one parameter is given, it specifies the maximum number of rows to return
from the beginning of the result set.
For example, to retrieve the first three rows, you can use the following query:
SELECT * FROM persons LIMIT 3;
To retrieve the rows 2-4 (inclusive) of a result set, you can use the following query:
SELECT * FROM persons LIMIT 1, 3;
Let's make a SQL query using the LIMIT clause in SELECT statement, after that we will execute this
query through passing it to the PHP mysqli_query() function to get the limited number of records.
Consider the following persons table inside the demo database:
+----+------------+-----------+----------------------+
| id | first_name | last_name | email
|
+----+------------+-----------+----------------------+
| 1 | Peter
| Parker
| peterparker@mail.com |
| 2 | John
| Rambo
| johnrambo@mail.com
|
| 3 | Clark
| Kent
| clarkkent@mail.com
|
| 4 | John
| Carter
| johncarter@mail.com |
| 5 | Harry
| Potter
| harrypotter@mail.com |
+----+------------+-----------+----------------------+
The PHP code in the following example will display just three rows from the persons table.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM persons LIMIT 3";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>first_name</th>";
echo "<th>last_name</th>";
echo "<th>email</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Close result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
After limiting the result set the output will look something like this:
+----+------------+-----------+----------------------+
| id | first_name | last_name | email
|
+----+------------+-----------+----------------------+
| 1 | Peter
| Parker
| peterparker@mail.com |
| 2 | John
| Rambo
| johnrambo@mail.com
|
| 3 | Clark
| Kent
| clarkkent@mail.com
|
+----+------------+-----------+----------------------+
Ordering the Result Set
The ORDER BY clause can be used in conjugation with the SELECT statement to see the data from a
table ordered by a specific field. The ORDER BY clause lets you define the field name to sort against and
the sort direction either ascending or descending.
The basic syntax of this clause can be given with:
SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC
Let's make a SQL query using the ORDER BY clause in SELECT statement, after that we will execute
this query through passing it to the PHP mysqli_query() function to get the ordered data. Consider the
following persons table inside the demo database:
+----+------------+-----------+----------------------+
| id | first_name | last_name | email
|
+----+------------+-----------+----------------------+
| 1 | Peter
| Parker
| peterparker@mail.com |
| 2 | John
| Rambo
| johnrambo@mail.com
|
| 3 | Clark
| Kent
| clarkkent@mail.com
|
| 4 | John
| Carter
| johncarter@mail.com |
| 5 | Harry
| Potter
| harrypotter@mail.com |
+----+------------+-----------+----------------------+
The PHP code in the following example selects all rows from the persons table and sorts the result by the
first_name column in the alphabetically ascending order.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution with order by clause
$sql = "SELECT * FROM persons ORDER BY first_name";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>first_name</th>";
echo "<th>last_name</th>";
echo "<th>email</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['first_name'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Close result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
After ordering the result, the result set will look something like this:
+----+------------+-----------+----------------------+
| id | first_name | last_name | email
|
+----+------------+-----------+----------------------+
| 3 | Clark
| Kent
| clarkkent@mail.com
|
| 5 | Harry
| Potter
| harrypotter@mail.com |
| 2 | John
| Rambo
| johnrambo@mail.com
|
| 4 | John
| Carter
| johncarter@mail.com |
| 1 | Peter
| Parker
| peterparker@mail.com |
+----+------------+-----------+----------------------+
Updating Database Table Data
The UPDATE statement is used to change or modify the existing records in a database table. This
statement is typically used in conjugation with the WHERE clause to apply the changes to only those
records that matches specific criteria.
The basic syntax of the UPDATE statement can be given with:
UPDATE table_name SET column1=value, column2=value2,... WHERE column_name=some_value
Let's make a SQL query using the UPDATE statement and WHERE clause, after that we will execute this
query through passing it to the PHP mysqli_query() function to update the tables records. Consider the
following persons table inside the demo database:
+----+------------+-----------+----------------------+
| id | first_name | last_name | email
|
+----+------------+-----------+----------------------+
| 1 | Peter
| Parker
| peterparker@mail.com |
| 2 | John
| Rambo
| johnrambo@mail.com
|
| 3 | Clark
| Kent
| clarkkent@mail.com
|
| 4 | John
| Carter
| johncarter@mail.com |
| 5 | Harry
| Potter
| harrypotter@mail.com |
+----+------------+-----------+----------------------+
The PHP code in the following example will update the email address of a person in the persons table
whose id is equal to 1.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt update query execution
$sql = "UPDATE persons SET email='peterparker_new@mail.com' WHERE id=1";
if(mysqli_query($link, $sql)){
echo "Records were updated successfully.";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
After update the persons table will look something like this:
+----+------------+-----------+--------------------------+
| id | first_name | last_name | email
|
+----+------------+-----------+--------------------------+
| 1 | Peter
| Parker
| peterparker_new@mail.com |
| 2 | John
| Rambo
| johnrambo@mail.com
|
| 3 | Clark
| Kent
| clarkkent@mail.com
|
| 4 | John
| Carter
| johncarter@mail.com
|
| 5 | Harry
| Potter
| harrypotter@mail.com
|
+----+------------+-----------+--------------------------+
Deleting Database Table Data
Just as you insert records into tables, you can delete records from a table using the SQL DELETE
statement. It is typically used in conjugation with the WHERE clause to delete only those records that
matches specific criteria or condition.
The basic syntax of the DELETE statement can be given with:
DELETE FROM table_name WHERE column_name=some_value
Let's make a SQL query using the DELETE statement and WHERE clause, after that we will execute this
query through passing it to the PHP mysqli_query() function to delete the tables records. Consider the
following persons table inside the demo database:
+----+------------+-----------+----------------------+
| id | first_name | last_name | email
|
+----+------------+-----------+----------------------+
| 1 | Peter
| Parker
| peterparker@mail.com |
| 2 | John
| Rambo
| johnrambo@mail.com
|
| 3 | Clark
| Kent
| clarkkent@mail.com
|
| 4 | John
| Carter
| johncarter@mail.com |
| 5 | Harry
| Potter
| harrypotter@mail.com |
+----+------------+-----------+----------------------+
The PHP code in the following example will delete the records of those persons from the persons
table whose first_name is equal to John.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt delete query execution
$sql = "DELETE FROM persons WHERE first_name='John'";
if(mysqli_query($link, $sql)){
echo "Records were deleted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
After the deletion the persons table will look something like this:
+----+------------+-----------+----------------------+
| id | first_name | last_name | email
|
+----+------------+-----------+----------------------+
| 1 | Peter
| Parker
| peterparker@mail.com |
| 3 | Clark
| Kent
| clarkkent@mail.com
|
| 5 | Harry
| Potter
| harrypotter@mail.com |
+----+------------+-----------+----------------------+
As you can see the records has been deleted successfully from the persons table.
#SECTION 2
Implementing User Authentication Mechanism
User authentication is very common in modern web application. It is a security mechanism that is used to
restrict unauthorized access to member-only areas and tools on a site.
In this tutorial we'll create a simple registration and login system using the PHP and MySQL. This tutorial
is comprised of two parts: in the first part we'll create a user registration form, and in the second part we'll
create a login form, as well as a welcome page and a logout script.
Building the Registration System
In this section we'll build a registration system that allows users to create a new account by filling out a
web form. But, first we need to create a table that will hold all the user data.
Step 1: Creating the Database Table
Execute the following SQL query to create the users table inside your MySQL database.
CREATE TABLE users (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
Please check out the tutorial on MySQL Database tutorial file in your resources folder for the detailed
information about syntax for creating tables in MySQL database system.
Step 2: Creating the Config File
After creating the table, we need create a PHP script in order to connect to the MySQL database server.
Let's create a file named "config.php" and put the following code inside it.
<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'demo');
/* Attempt to connect to MySQL database */
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
Step 3: Creating the Registration Form
Let's create another PHP file "register.php" and put the following example code in it. This example code
will create a web form that allows user to register themselves.
This script will also generate errors if a user tries to submit the form without entering any value, or if
username entered by the user is already taken by another user.
<?php
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate username
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} elseif(!preg_match('/^[a-zA-Z0-9_]+$/', trim($_POST["username"]))){
$username_err = "Username can only contain letters, numbers, and
underscores.";
} else{
$username = trim($_POST["username"]);
// Prepare a select statement
$sql = "SELECT id FROM users WHERE username = '$username'";
$stmt = mysqli_query($link, $sql) or die(mysqli_error($link));
if($stmt){
if(mysqli_num_rows($stmt) == 1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Validate password
if(empty(trim($_POST["password"]))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST["password"])) < 6){
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim($_POST["password"]);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = "Please confirm password.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if(empty($password_err) && ($password != $confirm_password)){
$confirm_password_err = "Password did not match.";
}
}
// Check input errors before inserting in database
if(empty($username_err) && empty($password_err) &&
empty($confirm_password_err)){
$password=password_hash($password, PASSWORD_DEFAULT);
// Prepare an insert statement
$sql = "INSERT INTO users (username, password) VALUES ('$username',
'$password')";
if($stmt = mysqli_query($link, $sql)){
header("location: login.php");
}
else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.cs
s">
<style>
body{ font: 14px sans-serif; }
.wrapper{ width: 360px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>Sign Up</h2>
<p>Please fill this form to create an account.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"
method="post">
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control <?php
echo (!empty($username_err)) ? 'is-invalid' : ''; ?>" value="<?php echo
$username; ?>">
<span class="invalid-feedback"><?php echo $username_err;
?></span>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control
<?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>" value="<?php echo
$password; ?>">
<span class="invalid-feedback"><?php echo $password_err;
?></span>
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="formcontrol <?php echo (!empty($confirm_password_err)) ? 'is-invalid' : ''; ?>"
value="<?php echo $confirm_password; ?>">
<span class="invalid-feedback"><?php echo
$confirm_password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-secondary ml-2"
value="Reset">
</div>
<p>Already have an account? <a href="login.php">Login
here</a>.</p>
</form>
</div>
</body>
</html>
The output of the above example (i.e. signup form) will look something like this:
From the above example, we have used the PHP's inbuilt password_hash() function to create a password
hash from the password string entered by the user (line no-78). This function creates a password hash
using a strong one-way hashing algorithm. It also generates and applies a random salt automatically
when hashing the password; this basically means that even if two users have the same passwords, their
password hashes will be different.
At the time of login we'll verify the given password with the password hash stored in the database using
the PHP password_verify() function, as demonstrated in the next example.
We've used the Bootstrap framework to make the form layouts quickly and beautifully. Please, checkout
the Bootstrap tutorial section to learn more about this framework.
Building the Login System
In this section we'll create a login form where user can enter their username and password. When user
submit the form these inputs will be verified against the credentials stored in the database, if the
username and password match, the user is authorized and granted access to the site, otherwise the login
attempt will be rejected.
Step 1: Creating the Login Form
Let's create a file named "login.php" and place the following code inside it.
<?php
// Initialize the session
session_start();
// Check if the user is already logged in, if yes then redirect him to
welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: welcome.php");
exit;
}
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = $login_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if username is empty
if(empty(trim($_POST["username"]))){
$username_err = "Please enter username.";
} else{
$username = trim($_POST["username"]);
}
// Check if password is empty
if(empty(trim($_POST["password"]))){
$password_err = "Please enter your password.";
} else{
$password = trim($_POST["password"]);
}
// Validate credentials
if(empty($username_err) && empty($password_err)){
// Prepare a select statement
$sql = "SELECT id, username, password FROM users WHERE username =
'$username'";
if($stmt = mysqli_query($link, $sql)){
// Check if username exists, if yes then verify password
if(mysqli_num_rows($stmt) == 1){
$obj=mysqli_fetch_object($stmt);
$hashed_password=$obj->password;
if(password_verify($password, $hashed_password)){
// Password is correct, so start a new session
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
// Redirect user to welcome page
header("location: welcome.php");
} else{
// Password is not valid, display a generic error
message
$login_err = "Invalid username or password.";
}
} else{
// Username doesn't exist, display a generic error
message
$login_err = "Invalid username or password.";
}
}
else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.cs
s">
<style>
body{ font: 14px sans-serif; }
.wrapper{ width: 360px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>Login</h2>
<p>Please fill in your credentials to login.</p>
<?php
if(!empty($login_err)){
echo '<div class="alert alert-danger">' . $login_err . '</div>';
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"
method="post">
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control <?php
echo (!empty($username_err)) ? 'is-invalid' : ''; ?>" value="<?php echo
$username; ?>">
<span class="invalid-feedback"><?php echo $username_err;
?></span>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control
<?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>">
<span class="invalid-feedback"><?php echo $password_err;
?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Login">
</div>
<p>Don't have an account? <a href="register.php">Sign up
now</a>.</p>
</form>
</div>
</body>
</html>
The output of the above example (i.e. login form) will look something like this:
Step 2: Creating the Welcome Page
Here's the code of our "welcome.php" file, where user is redirected after successful login.
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.cs
s">
<style>
body{ font: 14px sans-serif; text-align: center; }
</style>
</head>
<body>
<h1 class="my-5">Hi, <b><?php echo
htmlspecialchars($_SESSION["username"]); ?></b>. Welcome to our site.</h1>
<p>
<a href="reset-password.php" class="btn btn-warning">Reset Your
Password</a>
<a href="logout.php" class="btn btn-danger ml-3">Sign Out of Your
Account</a>
</p>
</body>
</html>
If data comes from external sources like form filled in by anonymous users, there is a risk that it may
contain malicious script indented to launch cross-site scripting (XSS) attacks. Therefore, you must escape
this data using the PHP htmlspecialchars() function before displaying it in the browser, so that any HTML
tag it contains becomes harmless.
For example, after escaping special characters the string <script>alert("XSS")</script> becomes
<script>alert("XSS")</script> which is not executed by the browser.
Step 3: Creating the Logout Script
Now, let's create a "logout.php" file. When the user clicks on the log out or sign out link, the script inside
this file destroys the session and redirect the user back to the login page.
<?php
// Initialize the session
session_start();
// Unset all of the session variables
$_SESSION = array();
// Destroy the session.
session_destroy();
// Redirect to login page
header("location: login.php");
exit;
?>
Adding the Password Reset Feature
Finally, in this section we will add the password reset utility to our login system. Using this feature logged
in users can instantly reset their own password for their accounts.
Let's create a file named "reset-password.php" and place the following code inside it.
<?php
// Initialize the session
session_start();
// Check if the user is logged in, otherwise redirect to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$new_password = $confirm_password = "";
$new_password_err = $confirm_password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate new password
if(empty(trim($_POST["new_password"]))){
$new_password_err = "Please enter the new password.";
} elseif(strlen(trim($_POST["new_password"])) < 6){
$new_password_err = "Password must have atleast 6 characters.";
} else{
$new_password = trim($_POST["new_password"]);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = "Please confirm the password.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if(empty($new_password_err) && ($new_password != $confirm_password)){
$confirm_password_err = "Password did not match.";
}
}
// Check input errors before updating the database
if(empty($new_password_err) && empty($confirm_password_err)){
$param_password=password_hash($new_password, PASSWORD_DEFAULT);
$param_id = $_SESSION["id"];
// Prepare an update statement
$sql = "UPDATE users SET password = '$param_password' WHERE id =
'$param_id'";
if($stmt = mysqli_query($link, $sql)){
session_destroy();
header("location: login.php");
exit();
}
else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Reset Password</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.cs
s">
<style>
body{ font: 14px sans-serif; }
.wrapper{ width: 360px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>Reset Password</h2>
<p>Please fill out this form to reset your password.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"
method="post">
<div class="form-group">
<label>New Password</label>
<input type="password" name="new_password" class="formcontrol <?php echo (!empty($new_password_err)) ? 'is-invalid' : ''; ?>"
value="<?php echo $new_password; ?>">
<span class="invalid-feedback"><?php echo $new_password_err;
?></span>
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="formcontrol <?php echo (!empty($confirm_password_err)) ? 'is-invalid' : ''; ?>">
<span class="invalid-feedback"><?php echo
$confirm_password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
<a class="btn btn-link ml-2" href="welcome.php">Cancel</a>
</div>
</form>
</div>
</body>
</html>
PHP has a rich collection of built-in functions for manipulating MySQL databases, strings, dates etc.
#SECTION 3: PHP FILE UPLOAD
Server-side file upload can be easily implemented using PHP. There are various ways available to upload
files to server and display them on the webpage e.g images, zip files, PDF files, document files, text files,
video files, audio files on a remote web server. Generally, in a dynamic web application, the uploaded file
is stored in a directory of the server and the file name is inserted in the database. Later, the files are
retrieved from the server based on the file name stored in the database and display on the web page.
The file can be uploaded directly to the database without storing on the server. But it will increase the
database size and web page load time. So, it’s always a good idea to upload images to the server and
store file names in the database. In this section, i will show you the entire process to upload and store
an image file in MySQL database using PHP.
Once the form is submitted information about the uploaded file can be accessed via PHP superglobal
array called $_FILES. For example, our upload form contains a file select field called photo (i.e.
name="photo")(see below), if any user uploaded a file using this field, we can obtains its details like the
name, type, size, temporary name or any error occurred while attempting the upload via the
$_FILES["file"] associative array, like this:





$_FILES["file"]["name"] — This array value specifies the original name of the file, including the file
extension. It doesn't include the file path.
$_FILES["file"]["type"] — This array value specifies the MIME type of the file.
$_FILES["file"]["size"] — This array value specifies the file size, in bytes.
$_FILES["file"]["tmp_name"] — This array value specifies the temporary name including full path
that is assigned to the file once it has been uploaded to the server.
$_FILES["file"]["error"] — This array value specifies error or status code associated with the file
upload, e.g. it will be 0, if there is no error.
NB: Before performing file uploads you need to ascertain that your server environment permits file
uploads and that you have necessary configurations set in php.ini file. Important configuration items
include: max_execution_time, memory_limit, file_uploads, upload_max_filesize ,and max_file_uploads
The example code demonstrates the process to implement the file upload functionality in the web
application and the following functionality will be implemented.




HTML form to upload image.
Upload image to server using PHP.
Store file name in the database using PHP and MySQL.
Retrieve images from the database and display in the web page.
Create Database Table
To store the image file name a table need to be created in the database. The following SQL creates an
images table with some basic fields in the MySQL database.
CREATE TABLE `images` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`uploaded_on` datetime NOT NULL,
`status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Database Configuration (config.php)
The config.php file is used to connect and select the MySQL database. Specify the database hostname
(DB_SERVER), username (DB_USERNAME), password (DB_PASSWORD), and name (DB_NAME) as
per your MySQL credentials.
<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'demo');
/* Attempt to connect to MySQL database */
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
Upload Form HTML
Create an HTML form to allow the user to choose a file they want to upload. Make sure <form> tag
contains the following attributes.


Also,
method="post"
enctype="multipart/form-data"
make sure <input> tag contains type="file" attribute.
<form action="upload.php" method="post" enctype="multipart/form-data">
Select Image File to Upload:
<input type="file" name="file">
<input type="submit" name="submit" value="Upload">
</form>
Output
The file upload form will be submitted to the upload.php file to upload image to the server.
Upload File to Server and Store in Database (upload.php)
The upload.php file handles the image upload functionality and shows the status message to the user.





Include the database configuration file to connect and select the MySQL database.
Get the file extension using pathinfo() function in PHP and validate the file format to check
whether the user selects an image file.
Upload image to server using move_uploaded_file() function in PHP.
Insert image file name in the MySQL database using PHP.
Upload status will be shown to the user.
<?php
// Include the database configuration file
include 'config.php';
$statusMsg = '';
// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir.$fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf');
if(in_array($fileType, $allowTypes)){
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
// Insert image file name into database
$insert = mysqli_query($link,"INSERT into images (file_name, uploaded_on)
VALUES ('".$fileName."', NOW())");
if($insert){
$statusMsg = "The file ".$fileName. " has been uploaded
successfully.";
}else{
$statusMsg = "File upload failed, please try again.";
}
}else{
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are
allowed to upload.';
}
}else{
$statusMsg = 'Please select a file to upload.';
}
// Display status message
echo $statusMsg;
?>
Look at this other example.
Create index.php - this is the main file containing user interface. It has an upload form and a HTML table
to display the list of uploaded files from database along with 'View' & 'Download' links for them.
<?php
include_once 'config.php';
// fetch files
$sql = "select file_name, uploaded_on from images";
$result = mysqli_query($link, $sql);
?>
<!DOCTYPE html>
<html>
<head>
<title>Upload View & Download file in PHP and MySQL | Demo</title>
<meta content="width=device-width, initial-scale=1.0" name="viewport" >
<link rel="stylesheet" href="css/bootstrap.css" type="text/css" />
</head>
<body>
<br/>
<div class="container">
<div class="row">
<div class="col-xs-8 col-xs-offset-2 well">
<form action="upload.php" method="post" enctype="multipart/formdata">
<legend>Select File to Upload:</legend>
<div class="form-group">
<input type="file" name="file" />
</div>
<div class="form-group">
<input type="submit" name="submit" value="Upload" class="btn
btn-info"/>
</div>
<?php if(isset($_GET['st'])) { ?>
<div class="alert alert-danger text-center">
<?php if ($_GET['st'] == 'success') {
echo "File Uploaded Successfully!";
}
else
{
echo 'Invalid File Extension!';
} ?>
</div>
<?php } ?>
</form>
</div>
</div>
<div class="row">
<div class="col-xs-8 col-xs-offset-2">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>#</th>
<th>File Name</th>
<th>View</th>
<th>Download</th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
while($row = mysqli_fetch_array($result)) { ?>
<tr>
<td><?php echo $i++; ?></td>
<td><?php echo $row['filename']; ?></td>
<td><a href="uploads/<?php echo $row['filename']; ?>"
target="_blank">View</a></td>
<td><a href="uploads/<?php echo $row['filename']; ?>"
download>Download</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
Create the upload.php file to perform the file upload logic
<?php
include('config.php');
//check if form is submitted
if (isset($_POST['submit']))
{
$filename = $_FILES['file']['name'];
//upload file
if($filename != '')
{
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$allowed = ['pdf', 'txt', 'doc', 'docx', 'png', 'jpg', 'jpeg',
'gif'];
//check if file type is valid
if (in_array($ext, $allowed))
{
// get last record id
$sql = 'select max(id) as id from images';
$result = mysqli_query($link, $sql);
if (count($result) > 0)
{
$row = mysqli_fetch_array($result);
$filename = ($row['id']+1) . '-' . $filename;
}
else
$filename = '1' . '-' . $filename;
//set target directory
$path = 'uploads/';
$created = @date('Y-m-d H:i:s');
move_uploaded_file($_FILES['file1']['tmp_name'],($path . $filename));
// insert file details into database
$sql = "INSERT INTO images(filename, uploaded_on) VALUES('$filename',
'$created')";
mysqli_query($link, $sql);
header("Location: index.php?st=success");
}
else
{
header("Location: index.php?st=error");
}
}
else
header("Location: index.php");
}
?>
Output
If file upload logic fails, the following message is returned. Else if, all goes well, the output in figure 2 is
shown.
Figure 1:Error message
Figure 2:Successful file upload
#SECTION 4: What is CRUD
CRUD is an acronym for Create, Read, Update, and Delete. CRUD operations are basic data
manipulation for database. We've already learned how to perform create (i.e. insert), read (i.e. select),
update and delete operations in previous sections. In this tutorial we'll create a simple PHP application to
perform all these operations on a MySQL database table at one place.
Well, let's start by creating the table which we'll use in our entire example.
Creating the Database Table
Execute the following SQL query to create a table named employees inside your MySQL database. We
will use this table for all of our future operations.
CREATE TABLE employees (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
address VARCHAR(255) NOT NULL,
salary INT(10) NOT NULL
);
Creating the Config File
After creating the table, we need create a PHP script in order to connect to the MySQL database server.
Let's create a file named "config.php" and put the following code inside it.
We'll later include this config file in other pages using the PHP require_once() function.
<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'demo');
/* Attempt to connect to MySQL database */
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
Creating the Landing Page
First we will create a landing page for our CRUD application that contains a data grid showing the records
from the employees database table. It also has action icons for each record displayed in the grid, that you
may choose to view its details, update it, or delete it.
We'll also add a create button on the top of the data grid that can be used for creating new records in the
employees table. Create a file named "index.php" and put the following code in it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.cs
s">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/fontawesome/4.7.0/css/font-awesome.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></
script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js">
</script>
<style>
.wrapper{
width: 600px;
margin: 0 auto;
}
table tr td:last-child{
width: 120px;
}
</style>
<script>
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
</script>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="mt-5 mb-3 clearfix">
<h2 class="pull-left">Employees Details</h2>
<a href="create.php" class="btn btn-success pullright"><i class="fa fa-plus"></i> Add New Employee</a>
</div>
<?php
// Include config file
require_once "config.php";
// Attempt select query execution
$sql = "SELECT * FROM employees";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo '<table class="table table-bordered tablestriped">';
echo "<thead>";
echo "<tr>";
echo "<th>#</th>";
echo "<th>Name</th>";
echo "<th>Address</th>";
echo "<th>Salary</th>";
echo "<th>Action</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['address'] .
"</td>";
echo "<td>" . $row['salary'] .
"</td>";
echo "<td>";
echo '<a href="read.php?id='.
$row['id'] .'" class="mr-3" title="View Record" data-toggle="tooltip"><span
class="fa fa-eye"></span></a>';
echo '<a href="update.php?id='.
$row['id'] .'" class="mr-3" title="Update Record" data-toggle="tooltip"><span
class="fa fa-pencil"></span></a>';
echo '<a href="delete.php?id='.
$row['id'] .'" title="Delete Record" data-toggle="tooltip"><span class="fa
fa-trash"></span></a>';
echo "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo '<div class="alert alert-danger"><em>No
records were found.</em></div>';
}
} else{
echo "Oops! Something went wrong. Please try again
later.";
}
// Close connection
mysqli_close($link);
?>
</div>
</div>
</div>
</div>
</body>
</html>
NB: In our class discussions, we have used a bootstrap admin dashboard, which already have the main
structure of our intended Electoral Management System. All required CSS and Javascript libraries
required for boostrap framework to work are already included in the package. In the example above,
those libraries are obtained externally using link and script elements in the HTML document .
Once employees table is populated with some records the landing page i.e. the CRUD data grid may look
something like the picture shown below:
Assignment
Using the above examples and illustrations, You should be able to create a prototype of an electoral
management system using the Bootstrap (Front-end) and PHP/MySql (Back -end). Kindly make sure you
have captured all relevant information for the voters.
You should also be in a position to upload user’s profile photo as part of data that is captured during
registration. Refer to PHP_BASICS_LECTURE2_4 file as well as PHP file uploads section [4] for more info.
System users: Voters, Admin
As per now, we expect that registered voters should be able to login to the system.
When a voter logs in to the system, he should be able to see his/her profile information.
Once the admin personnel logs in to the system, he/she should as well be able to see his/her profile
information. He should also have access to voter’s data management interfaces ie. Registration, Voter
listing, and (update and delete) action buttons.
Download