You are on page 1of 21

Chapter 8

Accessing MySQL Using PHP


Connection to MySQL Database
Three ways to connect to MySQL via PHP:
• Connect to MySQL using legacy PHP functions. It is only a
procedural style.
• Connect to MySQL using MySQL improved. It is both
procedural and object-oriented style.
• Connect to MySQL using PHP Data Objects (PDO). It is an
object-oriented style.

2
How to get info to and from a MySQL database
1. Establish a connection
2. Formulate a query
3. Submit the query
4. Process the result (for select statement)
5. Display output to the user
6. Disconnect from MySQL

3
Establish a connection
Before you can work with a database, you must
establish a relationship between your PHP program and
the database. This process involves identifying where
the database is and passing it a username and
password.

4
Establish a connection (cont…)
• To connect to database, we create an object (e.g., $conn) of
type mysqli (i stands for improvements) function which in
turn takes four arguments: host name, username, password,
and database name, respectively.
For example,
$conn = new mysqli ("localhost", "root", "123", "myDb");

5
Formulate a query
Have some sort of query or request you want to pass to the
database. For example, you may want to see all the data in a
particular table, or you may want to update a record. In either
case, you use SQL statement to prepare a request to pass to
the database.
$sql = "select * from tableName;";

6
Submit the query
After you build the query, you pass it (through the connection)
to the database. Assuming that the query is properly
formatted, the database processes the request and returns a
result.
$result = $conn->query ($sql);

N.B You can combine the last processes (Formulate a query


and Submit the query) into one step:
$result = $conn->query ("select * from tableName;");

7
Process the result
The database returns a special variable containing the results
of your query. You’ll generally need to pick through this
complex variable to find all the data it contains. For example,
it can contain hundreds of records.

8
Display output to the user
Most of the time, you’ll process the query results and convert
them to some sort of HTML display that the user can view.
Retrieve the results and output them to a web page
(fetch_assoc( ), fetch_row( ), or fetch_array( ), method).
For example, print id and name of the table:
if ($result->num_rows)
while ($row = $result->fetch_assoc())
echo ($row['id']. $row['name']);

9
Display output to the user
To display all data in the table:
while ($row = $result->fetch_assoc())
foreach ($row as $value)
echo ("$value, ");
Alternative way:
foreach($result as $row)
foreach($row as $value)
echo ($value);

10
Disconnect from MySQL
Use close( ) method to disconnect.
$conn->close( );

11
Print column name
• To print table’s column name as header, use fetch_fields( )
method of query object.
• For example, Alternative
$header = $result->fetch_fields(); foreach($result as $row) {
foreach($header as $value) foreach($row as $name=>$value)
echo($value->name); echo ($name);
break; //to exit the loop
}

12
Building and executing a query
• You can send a query to MySQL from PHP with mysqli
method using the query method of conn object. Once you
have an object returned in $result, you can use it to retrieve
the data you want, one item at a time, using the fetch_assoc,
fetch_row, or fetch_array method of the object.

13
fetch_assoc(), fetch_row(), fetch_array()
• fetch_assoc( ): fetches a result row as an associative array.
• fetch_row( ): fetches a result row as an enumerated
(numeric) array.
• fetch_array( ): fetches a result row as both an associative
and enumerated array.

Note that table column names in the database are case


sensitive.

14
Insert Statement
$sql = "insert into students values (6, 'Yahya Ahmed Farah', 'Shangani')";
if ($conn->query($sql))
echo ("Successfully registered");
else
echo ("Failed to register");
Insert using form
$sql = "insert into students (id, fulname, address) values ('$no', '$n',
'$add')";
if ($conn->query($sql))
echo ("<br>Successfully registered");
15
Update Statement
$sql = "update students set fulname = 'Timira Adan Jimcale',
address = 'Waabari' where id = 'C20186428'";
if ($conn->query($sql))
echo ("<br>Successfully updated");

16
Delete Statement
$no = 'C20186428';
$result = $conn->query ("select id from students where id =
'$no'");
if ($result->num_rows > 0) {
$sql = "delete from students where id = '$no'";
if ($conn->query($sql)
echo ("<br>Successfully deleted");
}

17
Delete Statement (cont…)
• At the end of the record:
echo("<td><a href='Delete.php?
Del=". $row['name']. "'>Delete</a>");

18
if (isset($_GET['Del'])) {
$name = $_GET['Del'];
require_once("Connection.php");
if (!$conn->connect_error) {
$result = $conn>query("select * from students where fullna
me = '$name'");
if ($result->num_rows > 0) {
$sql = "delete from students where fullname = '$name'";
if ($conn->query($sql)){
echo ("<br>has been deleted successfully.");
} } } }
19
Insert, update and delete,
• You can also do the same with insert, update and delete.

20
END
21

You might also like