Php stmt以另一种方式获得结果
我的一个查询示例Php stmt以另一种方式获得结果,php,mysqli,statements,Php,Mysqli,Statements,我的一个查询示例 public function db_query_select($query, $params, $param_types){ $dbc = $this->dbConnect(); if($stmt = $dbc->prepare($query)){ //prepared. //move the types to the front of the param array
public function db_query_select($query, $params, $param_types){
$dbc = $this->dbConnect();
if($stmt = $dbc->prepare($query)){
//prepared.
//move the types to the front of the param array
array_unshift($params, $param_types);
//call the bind param function with the parameters passed in by reference
//bind_param only allows by reference.
call_user_func_array(array($stmt, "bind_param"), $this->paramsToRefs($params));
//binded.
//attempt to execute the sql statement.
if ($stmt->execute()){
$result = $stmt->get_result();
$stmt->close();
$dbc->close();
return $result;
}
}
//must have failed...
return NULL;
}
如何更改stmt get_result();到没有本机驱动程序的共享服务器/主机接受的内容。。。mysqlnd
有人知道吗?无需更改使用此数据库函数的所有函数
谢谢
更新:::感谢@your common sense,请参阅答案
我相信这就是我想要的。希望它能帮助那些和我有同样问题的人。PDO对MySQLi,似乎更简单。。。没有用户调用func或类似的东西
数据库处理程序:
在DBHANDLER之外
PDO不仅比mysqli对用户友好得多,而且没有任何令人讨厌的缺点。因此,我强烈建议使用PDO而不是mysqli 使用DO时,您所追求的函数应该像这样简单
function run($sql, $args = NULL)
{
$pdo = ...;//your means of getting the connection variable
$stmt = $pdo->prepare($sql);
$stmt->execute($args);
return $stmt;
}
在获取函数的结果后,您可以将一个fetch方法链接到它的调用fetchColumn()
鉴于你的代码大部分是程序性的,让我建议你一个我写的非常好的例子。因此,完整的代码是:
$sql = "SELECT error_desc FROM nt_errors WHERE error_code = ?";
$errorText = DB::run($sql,[$code])->fetchColumn();
if (!$errorText){
$errorText = 'ERROR: Failed to retrieve error';
}
在这里,DB类是dbConnect()函数的更好替代品,run()方法是
DB\u query\u select()
的替代品,它实际上可以用于任何查询类型,包括插入、更新或任何内容。这是什么意思被服务器接受?当前结果不被接受?为什么这样认为?在本例中,没有理由prepare()
,只需调用$result=$dbc->query()
共享服务器没有安装mysqlnd本机驱动程序。我问过他们,根据php文档,这是使用get_result的一个要求只要使用PDO而不是mysqli,您的所有问题就会烟消云散就像我说的,您需要非常简单的代码。这里可以找到一个例子:惊人,简单得多。谢谢。正如你所说,这是一个非常简单的方法。限制是什么?它不能处理什么?嗯,说到run()函数,它不能用于多次执行。为此,必须使用DB::prepare(),如本文示例部分所示。对于DB类,没有任何限制,因为它支持PDO支持的所有东西。另一个限制是单例模式的常见限制。但是只要你的代码仍然是程序化的,使用它不会有什么坏处。谢谢,我已经把它全部转换成PDO了。但是,我使用的是$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);我试着在run函数和调用它的行中使用try-catch,但它什么都没有捕获。我得到的只是未捕获的PDO异常。有什么想法吗?我已经看过了。MySQLI刚刚在违反外键约束的删除中返回false,但PDO决定抛出实际错误。
function run($sql, $args = NULL)
{
$pdo = ...;//your means of getting the connection variable
$stmt = $pdo->prepare($sql);
$stmt->execute($args);
return $stmt;
}
$sql = "SELECT error_desc FROM nt_errors WHERE error_code = ?";
$errorText = DB::run($sql,[$code])->fetchColumn();
if (!$errorText){
$errorText = 'ERROR: Failed to retrieve error';
}