[英]Attach data in array in a php mysqli prepared statement
I am tyring to write a simple function here. 我想在这里写一个简单的函数。 The idea is to be able to call the function and display the data, but i am wondering if there is a way to stuff it into an array of some sort or something so that i can style the results when the function is called.
这个想法是为了能够调用该函数并显示数据,但是我想知道是否有一种方法可以将其填充到某种类型的数组中,以便在调用函数时可以设置结果的样式。 the function is as follows:
功能如下:
function getDBH() {
static $DBH = null;
if (is_null($DBH)) {
$DBH = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
}
return $DBH;
}
function selectInfo($limit, $offset){
$DBH = getDBH();
$stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?");
$stmt->bind_param("ii", $limit, $offset);
$stmt->execute();
$stmt->bind_result($id, $name, $email);
}
This replacement for your selectInfo()
function should return a multi-dimensional array containing one associative array per record. selectInfo()
函数的此替换应返回一个多维数组,每个记录包含一个关联数组。 It does not rely on you knowing before hand what fields are returned in the statement as that *
in the select statement can otherwise easily break things if you alter your table in any way. 它并不依赖您事先知道语句中返回的字段,因为如果您以任何方式更改表,则select语句中的
*
可能会轻易破坏事情。
function selectInfo($limit, $offset) { $DBH = getDBH(); $limit = (int) $limit; $offset= (int) $offset; $stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?"); $stmt->bind_param("ii", $limit, $offset); $stmt->execute(); // get all field info in returned set $result_metadata = $stmt->result_metadata(); $result_fields = $result_metadata->fetch_fields(); $result_metadata->free_result(); unset($result_metadata); $bind_array = array(); $current_row = array(); $all_rows = array(); foreach($result_fields as $val) { // use returned field names to populate associative array $bind_array[$val->name] = &$current_row[$val->name]; } // bind results to associative array call_user_func_array(array($stmt, "bind_result"), $bind_array); // continually fetch all records into associative array and add it to final $all_rows array while($stmt->fetch()) $all_rows[] = $current_row; return $all_rows; }
Edit: Changed up your
selectInfo()
function a bit as my previous answer was just too sloppy. 编辑:改变了您的
selectInfo()
函数,因为我以前的答案太草率。 print_r(selectInfo(0,10));
will print out all records with field names intact. 将打印出所有具有完整字段名称的记录。
$stmt->bind_result($id, $name, $email);
while (mysqli_stmt_fetch($stmt)) {
$row = array('id' => $id, 'name' => $name, 'email' => $email);
$rows[] = $row;
}
return $rows;
Use ! 采用 ! instead of ?
代替 ? to attach static data.
附加静态数据。 ?
? attaches quoted, escaped data.
附加带引号的转义数据。 !
! is unsafe, but not for limit.
是不安全的,但不是限制性的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.