I'm still new in PHP and I can't seem to run my simple test code when I do it OOP style. What my simple test program does is save your name, age and sex in the database.
It used to run when it was still in procedural style but when I do it OOP style it doesn't run any more. By the way I use MS SQL Server as my database.
Here's my PHP code with a file name of process.php:
<?php
class Connection {
public function connectDatabase() {
$serverName = "localhost";
$uid = "sa";
$pwd = "joseph04";
$databaseName = "Profile";
$connectionInfo = array( "UID"=>$uid, "PWD"=>$pwd, "Database"=>$databaseName);
// Connect using SQL Server Authentication
public $conn;
$conn = sqlsrv_connect( $serverName, $connectionInfo);
// Test Connection
if( $conn === false )
{
echo "Connection could not be established.\n";
die( print_r( sqlsrv_errors(), true));
}
}
}
class Insert extends Connection {
public function post() {
$Name = $_POST["NAME"];
$Age = $_POST["AGE"];
$Sex = $_POST["SEX"];
$sql = "INSERT INTO dbo.ProfileTable
(
Name,
Age,
Sex
)
VALUES
(
'$Name',
'$Age',
'$Sex'
)";
$parameters = array($Name, $Age, $Sex);
$stmt = sqlsrv_query($conn, $sql, $parameters);
if( $stmt === false ){
echo "Statement could not be executed.\n";
die( print_r( sqlsrv_errors(), true));
}
else {
echo "Rows affected: ".sqlsrv_rows_affected( $stmt )."\n";
}
// Free statement and connection resources
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
}
}
?>
And here's my HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Sample Form</title>
<link href="main1.css" rel="stylesheet" type="text/css">
</head>
<body>
<form method="post" action="process.php">
<table width="400" border="0">
<tr>
<td>Name:</td>
<td></td>
<td><input type="text" name = "NAME"></td>
</tr>
<tr>
<td>Age:</td>
<td></td>
<td><input type="text" name = "AGE"></td>
</tr>
<tr>
<td>Sex:</td>
<td></td>
<td><input type="text" name = "SEX"></td>
</tr>
</table>
<input type="submit" name="formSubmit" value="Submit!">
</form>
</body>
</html>
$o = new Insert(); $o->post();$obj = new Insert();called the method post like$obj->post(). And you have to call the connectDatabase method into post method. You can see the result. then