I'm simply trying this query in PHP for the temp table, but it's not working in PHP.
IF OBJECT_ID('tempdb..##t1') IS NOT NULL
DROP TABLE ##t1
select 'rec1' as col1 into ##t1;
select * from ##t1
PHP code:
$database = new SQL_DB;
$database->query(
"
IF OBJECT_ID('tempdb..##t1') IS NOT NULL
DROP TABLE ##t1
SELECT 'rec1' as col1 into ##t1;
SELECT * FROM ##t1;
"
);
$rows = $database->resultset();
SQL_DB class (simplified):
public function __construct(){
//Set DSN
$dsn = 'sqlsrv:Server=' . $this->host . ';Database=' . $this->dbname;
//Set options
/*$options = array(
PDO::ATTR_EMULATE_PREPARES => true,
PDO::SQLSRV_ATTR_ENCODING => PDO::SQLSRV_ENCODING_UTF8
);*/
$options = array(
PDO::SQLSRV_ATTR_QUERY_TIMEOUT => $this->TIMEOUT,
PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
);
//Create a new PDO instance
try {
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
// $this->dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
//Prepare statement
public function query($query) {
$this->stmt = $this->dbh->prepare($query);
}
//Return result Set
public function resultset($in = "") {
try{
if ($in == ""){
$this->stmt->execute();
}
else{
$this->stmt->execute($in);
}
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch (PDOException $e) {
$this->error = $e->getMessage();
}
}
It works just fine in Microsost SQL Server Management Studio and all other queries I've worked with in PHP work just fine so it's not any of the connection problem.
It definitely has something to do with the temp table and '#'.
What am I missing?
Update:
It works just fine if I split the query into 2 parts:
$database = new SQL_DB;
$database->query(
"
IF OBJECT_ID('tempdb..##t1') IS NOT NULL
DROP TABLE ##t1
SELECT 'rec1' as col1 into ##t1;
"
);
$database->resultset();
$database->query(
"
SELECT * from ##t1;
"
);
$rows = $database->resultset();