Php-mysql
Internet Tech & Website Design
Introduction
In this lesson, you will bring together your PHP and
SQL knowledge.
Target:
Script that connects to the dbms & selects a database
Script that creates a database.
Script that creates a table
Script to insert records in the table created
Script to extract records from the table
Open a Connection to MySQL
Before we can access database in the MySQL dbms, we need to be able to connect to
the server:
Connection string:
mysqli_connect(server_name, user_name, password)
To select an already existing database, u add database name as the 4 th parameter to
the connection string.
mysqli_connect(server_name, user_name, password, db_name)
Note:
The connection string must be included in every script which intends to interact with the
database.
The connection string used is for a test environment and not a live server, therefore default
credentials are used.
connect.php
<?php
$sn = "localhost";
$un = "root";
$pass = "";
// Create connection
$conn = mysqli_connect($sn, $un, $pass);
// Check connection
if(!$conn)
{
die('Not Connected!' .mysqli_connect_error());
}
?>
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
The CREATE DATABASE statement is used to create a
database in MySQL.
The following examples create a database named “y2023”
In this case we use connect.php on slide-4, note: no
database selection
<?php
//include connection string
include('connect.php');
//create database
$db="CREATE DATABASE y2023";
//execute sql query
$exedb = mysqli_query($conn, $db);
//check successfull db creation
if(!$exedb){
die("Database not created!" .mysqli_error($conn));
}
else{
echo 'Database created!';
}
?>
Note
After successfully creating the database “y2023”, the
connection string must change to include database
selection.
Note:
For all scripts below, we will include “conn.php” which is
an improvement of the connect.php.
The difference between the two scripts is that in conn.php
we also select the database in addition to connecting to
the DBMS.
conn.php
<?php
$sn = "localhost";
$un = "root";
$pass = "";
$db = “y2023";
// Create connection & select database
$conn = mysqli_connect($sn, $un, $pass, $db);
// Check connection
if(!$conn)
{
die('Not Connected!' .mysqli_connect_error());
}
?>
PHP Create table
<?php
//include connection
include('conn.php');
//create table
$tb="CREATE TABLE Student(
regno VARCHAR(17),
fname VARCHAR(20),
lname VARCHAR(20),
cw INT,
exam INT,
c_code VARCHAR(7),
PRIMARY KEY(regno)
)";
//execute sql query
$exetb = mysqli_query($conn, $tb);
//check successfull db creation
if(!$exetb){
die("Table not created!" .mysqli_error($conn));
}
else{
echo 'Table Student created!';
}
?>
PHP Insert Data Into MySQL
Insert Data Into MySQL database
After the database and table have been created, we can start
adding data to the table.
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 database table:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
OR
INSERT INTO table_name VALUES (value1, value2, value3,...)
in1.php
<?php
//include connection
include('conn.php');
//insert records into the student table
$in="INSERT INTO Student
VALUES(‘22/1/314/D/2309', ‘Anthony', ‘Kilyowa', 23, 33, 'IT201')";
//execute sql query
$exein = mysqli_query($conn, $in);
//check successful record insertion
if(!$exein){
die("Record not added!" .mysqli_error($conn));
}
else{
echo 'One record added to the student table!';
}
?>
Insertion from a form (in2.php)
<?php
//include connection
include('conn.php');
//capture data from the form
$regno=$_POST['regno'];
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$cw=$_POST['cw'];
$exam=$_POST['exam'];
$c_code=$_POST['c_code'];
//insert records into student table
$in="INSERT INTO Student
VALUES('$regno', '$fname', '$lname', $cw, $exam, '$c_code')";
//execute sql query
$exein = mysqli_query($conn, $in);
//check successfull db creation
if(!$exein){
die("Record not added!" .mysqli_error($conn));
}
else{
echo 'One record added to the student table!';
}
?>
HTML Form (post.html)
<form method="post" action=“in2.php">
<table align="left">
<tr>
<td>Registration Number:</td><td><input type="text"
name="regno"></td>
</tr>
<td>First Name:</td><td><input type="text" name="fname"></td>
</tr>
</tr>
<td>Last Name:</td><td><input type="text" name="lname"></td>
</tr>
</tr>
<td>Course Work:</td><td><input type="text" name="cw"></td>
</tr>
</tr>
<td>Exam:</td><td><input type="text"
name="exam"></td>
</tr>
</tr>
<td>Course Code:</td><td><input type="text"
name="c_code"></td>
</tr>
</tr>
<td colspan="2" style="text-align: right;"><input
type="submit" value="Post"> <input type="reset"
value="Delete"></td>
</tr>
</table>
</form>
Extraction (sel.php)
<?php
//include connection
include('conn.php');
//extract records
$sel="SELECT * FROM Student";
//execute sql query
$exesel = mysqli_query($conn, $sel);
//check if records exist in the students' table
if(mysqli_num_rows($exesel)>0)
{
while($row=mysqli_fetch_assoc($exesel))
{
//calculate final score as a derived attribute
$fs=$row['cw']+$row['exam'];
//print out records
echo "Registration Number:" .$row['regno']."<br>
First Name:" .$row['fname']."<br>
Last Name:" .$row['lname']."<br>
Course Code:" .$row['c_code']."<br>
Course Work:" .$row['cw']."<br>
Exam:" .$row['exam']."<br>
Final Score:" .$fs. "<br><br>";
}
}
else{
echo 'No records!';
}
?>
Close the Connection
The connection will be closed automatically when the
script ends otherwise you may use the following
function:
mysqli_close();
Example
mysqli_close($conn);
Note that this should come at the very end of your
script.