gpt4 book ai didi

PHP/MYSQLi 绑定(bind)结果

转载 作者:行者123 更新时间:2023-11-29 13:08:07 25 4
gpt4 key购买 nike

我正在为一个没有 mysqlnd 的网络写作。所以我需要快速更改所有代码以不使用它。我以为我有这个函数,但它重复了结果。

我非常感谢任何有关修复的帮助。

function getDBResults($sql, $params=array()) { // param 1 sql, param2 array of bind parameters
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_DATABASE);
if (!is_array($params)) {
$params = array($params);
}

$query = $con->stmt_init(); // $this->connection is the mysqli connection instance

// Start stmt
if($query->prepare($sql)) {

if (count($params)>0) { // Skip of there are no paremeters
// This will loop through params, and generate types. e.g. 'ss'
$types = '';
foreach($params as $param) {
if(is_int($param)) {
$types .= 'i'; //integer
} elseif (is_float($param)) {
$types .= 'd'; //double
} elseif (is_string($param)) {
$types .= 's'; //string
} else {
$types .= 'b'; //blob and unknown
}
}
array_unshift($params, $types);
// Bind Params
$bpArray = array($query,'bind_param');
$bpArray = 'mysqli_stmt_bind_param';

array_unshift($params, $query);

$tmp = array();
foreach($params as $key => $value) {
$tmp[$key] = &$params[$key];
};

call_user_func_array($bpArray, $tmp);
}

$query->execute();

// Get metadata for field names
$meta = $query->result_metadata();

// initialise some empty arrays
$fields = $results = array();

// This is the tricky bit dynamically creating an array of variables to use
// to bind the results
while ($field = $meta->fetch_field()) {
$var = $field->name;
$$var = null;
$fields[$var] = &$$var;
}

// Bind Results
call_user_func_array(array($query,'bind_result'),$fields);

// Fetch Results
while (mysqli_stmt_fetch($query)) {
call_user_func_array(array($query,'bind_result'),$fields);
$results[] = $fields;
}
$query->close();
// And now we have a beautiful
// array of results, just like
//fetch_assoc
return $results;
}
}

最佳答案

function getDBResults($sql, $params=array()) {
global $pdo; // you should NEVER connect in a function! But use already opened.
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
return $stmt->fetchAll();
}

看 - 三句简单的线。

here是您需要的所有信息。请记住,每个应用程序只需连接一次并始终使用此连接。

关于PHP/MYSQLi 绑定(bind)结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22428628/

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