i have this code to create a contact directory and my instructor wants me to create a function for database connect to minimize the coding and if an instance to change the server it is easy to change.
<?php
if(isset ($_POST ["add"])){
$name = $_POST['name'];
$address = $_POST['address'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$mobile = $_POST['mobile'];
}
class contactdirectory{
function db_connect(){ //database connection
$connect = mysql_connect("localhost", "root", "") or die ("Check your connection." . mysql_error());
mysql_select_db("contactdirectory");
}
function form(){
echo "<form name=contact method=post action=index.php>";
echo "Name:"."<input type=text name=name /><br />";
echo "Address:"."<input type=text name=address /><br />";
echo "Email"."<input type=text name=email /><br />";
echo "Tel No:"."<input type=text name=tel /><br />";
echo "Mobile No:"."<input type=text name=mobile /><br />";
echo "<input type=submit name=add value=Add />";
echo "</form>";
}
function add($name,$address,$email,$tel,$mobile){
$connectto -> db_connect();
$query = "INSERT INTO contact VALUES(0, '$name','$address','$email','$tel','$mobile')";
mysql_query($query,$connect);
$directory = new contactdirectory();
$directory -> form();
}
function delete($idno){
$connectto->db_connect();
$query="DELETE FROM contact WHERE idno=$idno";
mysql_query($query,$connect);
$directory = new contactdirectory();
$directory -> form();
}
function edit($idno){
$connect = mysql_connect("localhost", "root", "") or die ("Check your connection." . mysql_error());
mysql_select_db("contactdirectory");
$query = "SELECT * FROM contact WHERE idno=$idno";
$rs = mysql_query($query,$connect) or die (mysql_error());
if(mysql_num_rows($rs) > 0) {
while($row = mysql_fetch_assoc($rs)){
?>
<form name="contact" action="index.php" method="post">
Name:<input type="text" name="name1" value="<?php echo $row[name] ?>" /><br />
Address:<input type="text" name="address1" value="<?php echo $row[address] ?>" /><br />
Email:<input type="text" name="email1" value="<?php echo $row[email] ?>" /><br />
Tel No:<input type="text" name="tel1" value="<?php echo $row[tel] ?>" /><br />
Mobile No:<input type="text" name="mobile1" value="<?php echo $row[mobile] ?>" /><br />
<input type="hidden" name="idno" value="<?php echo $row[idno] ?>" />
<input type="submit" name="update" value="Update" />
</form>
<?php
}
}
}
function update(){
$connect = mysql_connect("localhost", "root", "") or die ("Check your connection." . mysql_error());
mysql_select_db("contactdirectory");
$query="UPDATE contact SET name='$_POST[name1]', address='$_POST[address1]', email='$_POST[email1]', tel='$_POST[tel1]', mobile='$_POST[mobile1]' WHERE idno='$_POST[idno]'";
$recordset=mysql_query($query,$connect) or die ('Update info error!' . mysql_error());
$directory = new contactdirectory();
$directory -> form();
}
}
?>
tnx.