[英]What's the right way to switch database using sqlsrv?
I'm starting to work with PHP 7 with mssql right now, and I was needing to switch the sql functions from mssql_ to sqlsrv_.我现在开始使用带有 mssql 的 PHP 7,我需要将 sql 函数从 mssql_ 切换到 sqlsrv_。 When I was using mssql functions, I was changing the database with the function mssql_change_db, but as I saw now, there are no alternatives functions to use instead of this function.
当我使用 mssql 函数时,我正在使用函数 mssql_change_db 更改数据库,但正如我现在看到的,没有替代函数可以代替此函数使用。 I thought to make this function buy myself, by using USE[DB] in every query but it seems to be useless or r ineffective.
我想通过在每个查询中使用 USE[DB] 来让这个函数自己购买,但它似乎没用或无效。 I've thought about another way, which seems to be better.
我想了另一种方法,似乎更好。
The another way that I've think about it's to add before every table name the DB_NAME.dbo.table.我想到的另一种方法是在每个表名之前添加 DB_NAME.dbo.table。
I have also started to build a function to that way, which finds the table name and adding automaticly the database name with the ".dbo" before the table name.我也开始以这种方式构建一个函数,它会找到表名并在表名之前自动添加带有“.dbo”的数据库名。
Here is what I did until now: ( I just started to build it )这是我到现在为止所做的:(我刚刚开始构建它)
It's just an example, of curse it's not finished yet.这只是一个例子,诅咒它还没有完成。
public function exec($mainQuery, $db = NULL)
{
if(isset($db)) {
$query = $mainQuery;
$query = explode('from ', $query);
$query = $query[1]; // Getting the rest of the query after the word "Form"
if (strpos($query, 'where') !== false) { // Checking if the rest of the query includes the word "Where"
$query = explode('where', $query); // Taking the word before the word "Where"
$tableName = $query[0];
}
else { // The rest of the query is actually the table name, because there is no "Where" in the query
$tableName = $query;
}
$pQuery = str_replace( "$tableName", " $db.dbo.$tableName", $mainQuery); // Replacing the table name with the DB.dbo.tablename
return sqlsrv_query($this -> sqlHandle, $pQuery);
}
else {
return sqlsrv_query($this -> sqlHandle, $mainQuery);
}
}
I should build it also for JOIN, INSERT (INTO), UPDATE.我也应该为 JOIN、INSERT (INTO)、UPDATE 构建它。
I don't know why, but I feel like it's bad way to do that,我不知道为什么,但我觉得这样做很糟糕,
that's why I ask you what's the better way to switch databases.这就是为什么我问你切换数据库的更好方法是什么。
Thanks in advance.提前致谢。
It is a not good idea to use USE Database
or some how change database in query, running from PHP (you did a really nice trick with DB names).使用
USE Database
或从 PHP 运行的查询中如何更改数据库不是一个好主意(您对数据库名称做了一个非常好的技巧)。 For that kind of stuff better use stored procedures and call them from PHP.对于那种东西,最好使用存储过程并从 PHP 调用它们。
In that case you don't need to think about in what schema or database your table is, that all is written in SP.在这种情况下,您无需考虑您的表是什么模式或数据库,所有这些都是用 SP 编写的。
One more way is to use one default database for all users, and use USE database
when you need to get table from not-default DB.另一种方法是为所有用户使用一个默认数据库,并在需要从非默认数据库获取表时使用
USE database
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.