gpt4 book ai didi

php - 使用 sqlsrv 切换数据库的正确方法是什么?

转载 作者:搜寻专家 更新时间:2023-10-30 23:37:36 26 4
gpt4 key购买 nike

我现在开始使用 PHP 7 和 mssql,我需要将 sql 函数从 mssql_ 切换到 sqlsrv_。当我使用 mssql 函数时,我正在使用函数 mssql_change_db 更改数据库,但正如我现在所看到的,没有其他函数可以替代此函数。我想通过在每个查询中使用 USE[DB] 来让这个功能自己买,但它似乎没有用或无效。我想过另一种方法,似乎更好。
我考虑过的另一种方法是在每个表名之前添加 DB_NAME.dbo.table。
我也已经开始以这种方式构建一个函数,它可以找到表名并自动添加数据库名称,并在表名前加上“.dbo”。
这是我到目前为止所做的:(我刚刚开始构建它)
这只是一个例子,诅咒它还没有完成。

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);
}
}


我还应该为 JOIN、INSERT (INTO)、UPDATE 构建它。
我不知道为什么,但我觉得这样做很糟糕,
这就是为什么我问你切换数据库的更好方法是什么。
提前致谢。

最佳答案

使用 USE Database 或一些如何在查询中更改数据库,从 PHP 运行(您对数据库名称做了一个非常好的技巧)不是一个好主意。对于那种东西最好使用存储过程并从 PHP 调用它们。

在那种情况下,你不需要考虑你的表是在什么模式或数据库中,所有都是用 SP 编写的。

另一种方法是为所有用户使用一个默认数据库,并在需要从非默认数据库获取表时使用USE database

关于php - 使用 sqlsrv 切换数据库的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39808107/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com