Sunday, May 17, 2009

Exercise 8: PHP and MySQL database access

  1. Start with a simple table in the database:
    mysql> SELECT * FROM employees;
  2. Create a web page with the following PHP:
    <?php
    $db = mysql_connect(“farrer.csu.edu.au", “keustace", “password");
    mysql_select_db(“mydatabase",$db);
    $result = mysql_query("SELECT * FROM employees",$db);
    echo "First Name: ", mysql_result($result,0,"first"), "<BR>";
    echo "Last Name: ", mysql_result($result,0,"last"), "<BR>";
    echo "Address: ", mysql_result($result,0,"address"), "<BR>";
    echo "Position: ", mysql_result($result,0,"position"), "<BR>";
    ?>
    My password is included? We look at security later…☺
  3. This is how we can add a record and is part of a file to create called add_record.html
    <HTML>
    <BODY>
    <FORM METHOD="POST" ACTION="add_record.php">
    First name:<INPUT TYPE="Text" NAME="first"><br>
    Last name:<INPUT TYPE="Text" NAME="last"><br>
    Address:<INPUT TYPE="Text" NAME="address"><br>
    Position:<INPUT TYPE="Text" NAME="position"><br>
    <INPUT TYPE="Submit" NAME="submit" VALUE="Enter information">
    </FORM>
    </BODY>
    </HTML>
  4. The corresponding PHP file is add_record.php used with the POST method:
    <?php $db = mysql_connect(“farrer.csu.edu.au", “keustace", "password");
    mysql_select_db(“mydatabase",$db);
    $result = mysql_query("INERT INTO employees (first,last,address,position) VALUES ('$first','$last','$address','$position')");
    if ($result == 1) { echo "Thank you! Your information has been entered.“;
    } else {
    echo "Sorry, there's a problem";
    }
    ?>
  5. The last code example shows how to get multiple records:
    <?php
    $db = mysql_connect(“farrer.csu.edu.au", “keustace", "password");
    mysql_select_db(“mydatabase",$db);
    $result = mysql_query("SELECT * FROM employees",$db);
    echo "<table border=1>\n";
    echo "<tr><td><b>Name</b></td><td><b>Position</b></tr>\n";
    while ($myrow = mysql_fetch_row($result)) {
    echo "<tr><td>", $myrow[2], ", ", $myrow[1], "</td><td>", $myrow[3], "</td></tr>";
    }
    echo

No comments:

Post a Comment