I'm writing for a web, that does not have mysqlnd. So I need to quickly change all my code to not use it. I thought I was there with this function, but it repeats results.
I would really appreciate any help as to the fix.
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();
}
see - three simple lines.
here is all the info you need. Just remember you have to connect only once per application and use this connection all the way.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.