【发布时间】:2014-05-22 10:01:29
【问题描述】:
我还是 PHP 新手,当我执行 OOP 样式时,我似乎无法运行我的简单测试代码。我的简单测试程序所做的就是将您的姓名、年龄和性别保存在数据库中。
它曾经在程序样式中运行,但当我执行 OOP 样式时,它不再运行。顺便说一句,我使用 MS SQL Server 作为我的数据库。
这是我的 PHP 代码,文件名为 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);
}
}
?>
这是我的 HTML 代码:
<!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(); -
哦,我没有这些,我该怎么做?请帮忙?谢谢你的回复..
-
在你的表单动作文件中首先创建一个 Class Insert Like
$obj = new Insert();的实例,调用方法 post like$obj->post()。您必须将 connectDatabase 方法调用到 post 方法中。你可以看到结果。那么 -
感谢@biswajitGhosh 对我的帮助! :)
标签: php html sql-server oop