Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 20

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
5. Display output to the user
6. Disconnect from MySQL

3
Cont…
• 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
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, user name, password,
and database name respectively.
For example,
$conn = new mysqli ("localhost", "root", "123", "myDb");

5
Cont…
• 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 to
prepare a request to pass to the database.
$sql = "select * from tableName";

6
Cont…
• 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);

7
Cont…
• 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
Cont…
• 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( ), fetch_array( ), method).
while ($row = $result->fetch_assoc())
echo ($row['id']. " ". $row['name']. "<br>");
Alternative:
foreach($result as $row)
foreach($row as $name=>$value)
echo ($value); 9
Cont…
Disconnect from MySQL
Use close( ) method to disconnect.
$conn->close( );

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

11
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.

• Note that table column names in the database are case sensitive.

12
fetch_array(), fetch_assoc(), fetch_row()
The difference is that:
• 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 an associative, an
enumerated array, or both.

13
Insert Statement
$sql = "insert into students values (6, 'Yahya Ahmed Farah',
'Shangani')";
if ($conn->query($sql) == true)
echo ("Successfully registered");
Insert using form
$sql = "insert into students (id, fulname, address) values ('$no', '$n',
'$add')";
if ($conn->query($sql))
echo ("<br>Successfully registered");

14
Update Statement
$sql = "update students set fulname = 'Timira Adan Jimcale',
address = 'Waabari' where id = 'C20186428'";
if ($conn->query($sql) == true)
echo ("<br>Successfully updated");

15
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'";
$conn->query($sql);
echo ("<br>Successfully deleted");
}

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

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

19
END
20

You might also like