PHP Part 2

Access MySQL Database by using PHP

Function name Notes
mysql_connect Open a connection to a MySQL Server, it accepts parameter of server name, username, password...etc. If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The link to the server will be closed as soon as the execution of the script ends. Return an MySQL link identifier if successful

 

mysql_pconnect Open a persistent connection to a MySQL server, act similar to mysql_connect() except;
  • when connecting, the function would first try to find a (persistent) link that's already open with the same parameter. If one is found, an identifier for it will be returned instead of opening a new connection.
  • the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use
mysql_close Close MySQL connection but isn't usually necessary, as non-persistent open links are automatically closed at the end of the script's execution.

 

mysql_select_db  Select a MySQL database by accepting 2 parameters, the name of database and the database link identifier

 

mysql_query Submit a MySQL query to the database,  returns a resource identifier if successful

mysql_fetch_array Fetch the  result row as an array.  Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.

Steps to communicate with MySQL:

  1. Establish a connection to the database 
  2. Select the database to be used
  3. Submit a query (e.g. SELECT * FROM student in the sample program below)
  4. Fetch the result. (e.g. The result is stored in the array $row. $row["sid"] stores the value of field sid of a particular record (row) ) 
<html>
<head><title>Student enquiry</title></head>

<body>
<p>List all student records, please click submit: </p>
<form method="post" action="student.php">
<p><input type="submit" name="Submit" value="Submit"></p>

</form>
</body>
</html>
student.php
<html><head><title>PHP Test</title></head>
<body>
<?php
//Connect to the database on the server's machine as user "root". 

$conn = mysql_connect("localhost", "root", ""); 
mysql_select_db("course", $conn);
$res = mysql_query("SELECT * FROM student", $conn); 
?>

<table border=1>
<tr><th>Student ID</th><th>Student Name</th><th>Age</th>
<?php while ($row = mysql_fetch_array($res)){
  print "<tr>"; 
  print ("<td>".$row["sid"]."</td>");
  print ("<td>".$row["sname"]."</td>");
  print ("<td>".$row["age"]."</td><tr>");
}
?>
</table>
</body></html>
Result :display on browser after clicked the SUBMIT button:

<html>
<head><title>Student enquiry</title></head>

<body>
<p><font size="5">Search for record, please input name and click submit: </font></p>
<form method="post" action="student1.php">
<p>Input Name: <input type="text" name ="inputname" value ="">
</p>
<p>
<input type="submit" name="Submit" value="Submit">
</p>

</form>
</body>
</html>

Note 1  : 
Variable inputname is passed in the query string as $_POST["inputname"]

Note 2  : 
$_POST
autoglobal contains all POST data. Use $_GET autoglobal if method GET is used, use the $_REQUEST autoglobal if you don't care the source of your request data.

student1.php 

<html><head><title>PHP Test</title></head>
<body>
<?php
//Connect to the database on the server's machine as user "root". 

$conn = mysql_connect("localhost", "root", ""); 
mysql_select_db("course", $conn);
$res = mysql_query("SELECT * FROM student where sname = '". $_POST["inputname"] ."'", $conn); 
?>

<table border=1>
Records of table "student"
<tr><th>Student ID</th><th>Student Name</th><th>Age</th>
<?php while ($row = mysql_fetch_array($res)){

print "<tr>";
print ("<td>".$row["sid"]."</td>");
print ("<td>".$row["sname"]."</td>");
print ("<td>".$row["age"]."</td><tr>");
}
?>
</table>
</body></html>

Result :display on browser if "Peter Pan" is input to the textbox:

 


Hypertext Transfer Protocol (HTTP)


State management - to store the session information

Methods to propagating session information to the client


Embedding it in a URL


Embedding it in a hidden field of a form


Using Cookie

Set-Cookie:
UIDC=61.18.6.248:0990120596:499272;
domain=.netscape.com;path=/;expires=31-Dec-2010

 

Set cookie in PHP

Setcookie($n_name,$name,time( )+3*24*3600 )

A simple feedback form which records the date and time that the user logged into the system and saves this information, in addition to the user's name and email address, in several cookies.


Comparison of different methods for propagation session information

 

Embedding sessions information in URLs

Embedding sessions information in hidden field

Use of cookies

Ease of entry to an old session

Yes, by bookmark the URL which includes the session id

No.

Yes, if a cookie has not expired

Distinguish 2 sessions of the same machine

Yes

Yes

No

Reliability

No, user can alter the session id of the URL

A little bit more difficult to change the session id

No, the user can reject cookies

 


Session management in PHP

<A HREF="link.php?<?=SID?>">


Steps to manage a session:

  1. Start a session 
    session_start(); 
  2. Register session variable 
    //assign value to session variable
    $myvar=5;
    session_register("myvar");

    // register more than one session variables
    session_register("myvar1","myvar2");

  1. Using session variable
    // to check whether session variable is registered, return true if so, false otherwise.
    $result = session_is_registered("myvar"); 

    echo $myvar;

  2. Remove session variable and close a session
    // to remove session variable
    session_unregistered("myvar"); 

    // to remove all session variables
    session _unset();

    // to close a session
    session_destroy();

<?
session_start();
session_register("sess_var");

$sess_var="Hello world!";
echo "The content of \$sess_var is $sess_var<br>";
?>

<a href = "page2.php">Next page</a>

page2.php

<?
session_start();
echo "The content of \$sess_var is $sess_var<br>";
session_unregister("sess_var");
?>

<a href = "page3.php">Next page</a>

page3.php

<?
session_start();
echo "The content of \$sess_var is $sess_var<br>";
session_destroy();
?>

                    Result:

 

 

<?php

   session_start();
   if (!session_is_registered("count")) {
       session_register("count");
        $count = 1;
        }
     else {
         $count++;
          }
?>

Hello visitor, you have seen this page <?php echo $count; ?> times.<p>
To continue, <A HREF="nextpage1.php?<?=SID?>">click here</A>

Result:

 

 


References