Chapter 4 - Data Base Manipulation Using PHP
Chapter 4 - Data Base Manipulation Using PHP
PHP
Chapter 4
1
2
A Relational DataBase Management
System (RDBMS)
Enables you to implement a database with tables, columns
and indexes.
Guarantees the Referential Integrity between rows of
various tables.
Updates the indexes automatically.
Interprets an SQL query and combines information from
various tables
3
RDBMS Terminology:
Database: A database is a collection of tables, with related data.
Table: A table is a matrix with data
Column: One column (data element) contains data of one and the
same kind, to represent one property of an entity
Row: A row (= tuple, entry or record) is a group of related data, to
represent one instance of an entity
Redundancy: Storing data twice, redundantly to make the system
faster.
Primary Key: A primary key is unique. A key value can not occur
twice in one table. With a key, you can find at most one row.
Foreign Key: A foreign key is the linking pin between two tables
Constraints: rules set over database elements
4
Introduction to MySQL
MySQL is a RDBMS
Is an open-source software
Use standard form of SQL data language
supports large databases, up to 50 million rows or
more in a table
The MySQL command line monitor Creating database
tables Queries
5
Basic queries
CREATE: create databases and tables
CREATE TABLE tableName(columnName Datatype constraint, …. );
SELECT: select table rows based on certain conditions
SELECT columnName, columnName… FROM tableName WHRER condition;
DELETE: delete one or more rows of a table
DELETE FROM tableName WHERE condition;
INSERT: insert a new row in a table
INSERT INTO tableName(column list) VALUES (column values);
UPDATE: update rows in a table
UPDATE tableName SET columnName = NewValues;
ALTER: alter the structure of a table
ALTER TABLE tableName ADD columnBame dataType;
ALTER TABLE tableName DROP columnName;
ALTER TABLE tableName MODIFY columnName Datatype [NULL value] [DEFAULT value];
ALTER TABLE tableName CHANGE old_columnName new_columnName datatype;
ALTER TABLE tableName RENAME TO new_tableName;
6
Administrative MySQL Command:
USE Databasename: This will be used to select a particular
database in MySQL work area.
SHOW DATABASES: Lists the databases that are accessible by
the MySQL DBMS.
SHOW TABLES: Shows the tables in the database once a
database has been selected with the use command.
SHOW COLUMNS FROM tablename: Shows the attributes,
types of attributes, key information, whether NULL is permitted,
defaults, and other information for a table.
SHOW INDEX FROM tablename: Presents the details of all
indexes on the table, including the PRIMARY KEY.
SHOW TABLE STATUS LIKE tablename\G: Reports details of
the MySQL DBMS performance and statistics.
7
PHP and MySQL functions
Connecting to a Database
Making a query
Using results of a query
Freeing resources
closing the connection
8
Connecting to a Database
$servername=“servername:port";
$username=“mysql_user_name“;
$password=“mysql_password";
$dbname=“database_name“;
$con = mysqli_connect($servername, $username, $password, $dbname);
10
Making a query (1. SELECT)
$query="SELECT SID, StudName, age, sex FROM student";
$result=mysqli_query($con, $query);
$row_record=mysqli_fetch_row()
/*each call returns the next row as an indexed array where result is a resource
returned from a call to mysqli_query (FALSE if no more rows)*/
$row_record=mysqli_fetch_assoc($result);//record set
/*as in mysql_fetch_row but next row is returned as an associative array*/
$row_record=mysqli_fetch_array(result)
/*combines mysqli_fetch_row, mysqli_fetch_assoc
returns
13 row information as both an associative array and an indexed array*/
Example PHP for DB query (SELECT)
<?php
function viewData($dbname){
$dbname= $dbname;
$con = connect_db($dbname);
$sql = "SELECT SID, StudName, age, sex FROM student";
$result=mysqli_query($con, $sql);
if(mysqli_num_rows($result)>0){
echo "<table border='1'><th>ID</th><th>NAME</th><th>AGE</th><th>SEX</th>";
while($row=mysqli_fetch_assoc($result)){
echo
"<tr><td>".$row["SID"]."</td><td>".$row["StudName"]."</td><td>".$row["age"]."</td><td>".$row["sex"].
"</td></tr>";
}
echo "</table>";
}
else{
echo "no record found";
}
}
14
?>
Freeing query resources
mysqli_free_result($result)
free memory associated with the given resource
called result (after a select query).
Not necessary except for large result sets
Done automatically when script exits.
15
closing the connection
mysqli_close($con)
close the database connection associated with
the given database link, ($con).
16
Error handling
mysqli_connect_errno()
Returns the last error code number from the last call to
mysqli_connect
An error code value for the last call to mysqli_connect, if it
failed.
zero means no error occurred
mysqli_connect_error
Returns a string description of the last connect error
NULL is returned if no error occurred.
17
Other functions
mysqli_real_escape_string($con, $ escapeString);
This function is used to create a legal SQL string that you
can use in an SQL statement.
The given string is encoded to an escaped SQL string,
taking into account the current character set of the
connection.
parameters
$con: a link identifier returned by mysqli_connect
$escapeString: the string to be escaped.
Characters encoded are NUL (ASCII 0), \n, \r, \, ', ", and Control-Z.
18
Student register example
First create a database and the table
CREATE DATABASE sampledb;
USE sampledb;
CREATE TABLE student
(
SID int PRIMARY KEY NOT NULL AUTOINCREMENT,
studName varchar(50),
sex varchar(10),
age int
);
19
Insert.html (insert.php)
<html>
<body>
<fieldset>
<legend><h1>Register here...</h1></legend>
<form action="register.php" method="post">
Name: <input type="text" name="name"><br><br>
ID: <input type="text" name="id"><br><br>
Sex: <input type="text" name="sex"><br><br>
Age: <input type="text" name="age"><br><br>
<input type="submit" value="insert"><br><br>
</form>
</fieldset>
</body>
</html>
20
Register.php
<?php
$studname= mysqli_real_escape_string($con, $_POST['name']);
$age=mysqli_real_escape_string($con, $_POST['age']);
$sex=mysqli_real_escape_string($con, $_POST['sex']);
$sid=mysqli_real_escape_string($con, $_POST['id']);
$sql = "INSERT INTO student (StudName, age, sex, SID) VALUES ('$studname',
'$age', '$sex', '$sid')";
if (!mysqli_query($con, $sql)) {
$err=1;
}
mysqli_close($con);
if(isset($err)){
header("location: index.html?err=1");
}
else{
header("location: index.html");
}
?> 21
View.php
<?php require_once('connect_db.php')?>
<html>
<body>
<?php
$dbname="sampledb";
$con = connect_db($dbname);
$sql = "SELECT SID, StudName, age, sex FROM student";
$result=mysqli_query($con, $sql);
if(mysqli_num_rows($result)>0){
echo "<table border='1'><th>ID</th><th>NAME</th><th>AGE</th><th>SEX</th>";
while($row=mysqli_fetch_assoc($result)){
Echo"<tr><td>".$row["SID"]."</td><td>".$row["StudName"]."</td><td>".$row["age"]."</td><td>".$row["sex"]."</td></t
r>";
}
echo "</table>";
}
else{
echo "no record found";
}
mysqli_close($con);
?>
22
</body></html>
Question
23