我有以下课程:
<?php
require_once($_SERVER['DOCUMENT_ROOT']. '/wp-content/themes/quest/wahoo/common.php');
class TestingClass
{
private function InsertUser()
{
$query = "EXEC dbo.InsertUser @Title = @sTitle, -- varchar(50)
@FirstName = @sFirstName, -- varchar(100)
@MiddleName = @sMiddleName, -- varchar(100)
@LastName = @sLastName, -- varchar(100)
@Gender = @sGender, -- varchar(20)
@DOB = @sDOB, -- datetime
@Email = @sEmail, -- varchar(200)
@Phone = @sPhone, -- varchar(50)
@Mobile = @sMobile, -- varchar(50)
@HomeAddress = @sHomeAddress, -- varchar(100)
@HomePostCode = @sHomePostCode, -- varchar(10)
@HomeSuburb = @sHomeSuburb, -- varchar(50)
@HomeState = @sHomeState, -- varchar(20)
@HomeCountry = @sHomeCountry, -- varchar(200)
@BrowserDetails = @sBrowserDetails, -- varchar(500)
@IsActive = @sIsActive, -- bit
@Password = @sPassword, -- varchar(500)
@Salt = @sSalt, -- varchar(50)
@LastLogin = GETDATE(), -- datetime
@CompanyID = @sCompanyId, -- int
@Created = GETDATE(), -- datetime
@CreatedBy = user, -- varchar(50)
@LastModified = NULL, -- datetime
@LastModifiedBy = NULL, -- varchar(50)
@UserName = @sUserName, -- varchar(50)
@UserRole = 'user' -- varchar(30)";
$query_params = array(
':username' => $_POST['username']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// display json encode on the page for AJAX to read
echo json_encode($result);
}
}
?>
哪一行:
$stmt = $db->prepare($query);
我正在尝试使用我公共文件中的以下PDO变量:
$db = new PDO ("sqlsrv:server = tcp:$host; Database = $dbname", "$username", "$password");
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
我可以在类之外做到这一点,但是一旦我在类方法中并尝试使用$ db,我就会被告知该变量未定义。有没有办法我仍然可以这样做而不必使用全局变量(特别是因为我想将我的公共文件移到wwwroot之外)?
答案 0 :(得分:4)
将您的变量传递给您的班级:
class TestClass {
private $db = null;
public function __construct($db){
$this->db = $db;
}
public function executeSomething(){
// you can now use $this->db as your PDO object
// $db = $this->db;
// $stmt = $db->prepare('sql code');
}
}
$db = new PDO('...');
$instance = new TestClass($db);
$instance->executeSomething();