我试图使用PHP从数据库中获得数组结构的结果。为此,我使用以下代码:
config。:
$mysqli = new mysqli("localhost", "root", "root", "databasename");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
}
database.class.php :
class database
{
function __construct($mysqli)
{
$this->mysqli = $mysqli;
}
/*
* Utility function to automatically bind columns from selects in prepared statements to
* an array
*/
function bind_result_array($stmt)
{
$meta = $stmt->result_metadata();
$result = array();
while ($field = $meta->fetch_field())
{
$result[$field->name] = NULL;
$params[] = &$result[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $params);
return $result;
}
/**
* Returns a copy of an array of references
*/
function getCopy($row)
{
return array_map(create_function('$a', 'return $a;'), $row);
}
function select($campos, $tabela, $condicao='')
{
$query = 'SELECT '.$campos.' FROM '.$tabela;
if(trim($condicao!='')){
$query.=' WHERE '.$condicao;
}
$stmt = $this->mysqli->prepare($query);
$stmt->execute();
$row = $this->bind_result_array($stmt);
if(!$stmt->error)
{
while($stmt->fetch())
$dados[] = $this->getCopy($row);
}
return $dados;
}
要使用它,我可以这样做:
$data = $db->select('*', 'users', 'idlevel = 1 LIMIT 10');
这个$data
将返回一个数组,就像这样:
[1]=>
array(6) {
["id"]=>
int(17)
["nome"]=>
string(13) "Gareth Barlow"
["email"]=>
string(30) "sit.amet@semPellentesqueut.net"
["idnivel"]=>
int(1)
["password"]=>
string(0) ""
["departamento"]=>
NULL
}
[2]=>
array(6) {
["id"]=>
int(20)
["nome"]=>
string(9) "John Lara"
["email"]=>
string(13) "odio@arcu.net"
["idnivel"]=>
int(1)
["password"]=>
string(0) ""
["departamento"]=>
NULL
}
但是,如果我在$data"
行之后执行另一个数据库调用,例如:
$foo = $db->select('*', 'users', 'idlevel = 2 LIMIT 10');
浏览器尝试返回数据,但在短时间内,它给我"连接被重置(…)"。
有任何方法来执行这些查询并返回两个像这样的数组吗?
更新1
好了,我想我找到解决这个问题的办法了。
function select($campos, $tabela, $condicao='')
{
$query = 'SELECT '.$campos.' FROM '.$tabela;
if(trim($condicao!='')){
$query.=' WHERE '.$condicao;
}
$result = $this->mysqli->query($query);
if ($result = $this->mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$dados[] = $this->getCopy($row);
}
return $dados;
$result->free();
}
}
这允许我使用来做同样的事情,没有错误。谢谢大家;)
我认为你需要关闭语句对象…
在select函数中,在
return $dados;
make a
$stmt->close();
简单地使用不同的对象如何?
$db1 = new Database($mysqli);
$data1 = $db->select('*', 'users', 'idlevel = 1 LIMIT 10');
$db2 = new Database($mysqli);
$data2 = $db->select('*', 'users', 'idlevel = 1 LIMIT 10');
class Post extends Eloquent {
它不能解决数据库类中的潜在问题,但它应该为您争取时间寻找替代方案。老实说,你现在用的这个看起来没什么用。