仅在$ i = 0时有效;
<?php
include 'db.php';
$con = new db();
$db = $con->getConnection();
$i = 0;
while($i <= 10){
$query = "call rep_summary('$date')";
$result = $db->query($query);
while ($data = $result->fetch_assoc()) {
$user = $data['username'];
$id = $data['id'];
echo $user;
}
$i++;
}
$db->close();
?>
以下代码工作正常,但需要花费太多时间,因此我想重用连接
<?php
include 'db.php';
$i = 0;
while($i <= 10){
$con = new db();
$db = $con->getConnection();
$query = "call rep_summary('$date')";
$result = $db->query($query);
while ($data = $result->fetch_assoc()) {
$user = $data['username'];
$id = $data['id'];
echo $user;
}
$i++;
}
$db->close();
?>
和db class
<?php
class db {
var $_host = "localhost";
var $_user = "root";
var $_password = "";
var $_database = "test";
var $db;
public function __construct() {
$this->db = new mysqli($this->_host, $this->_user, $this->_password, $this->_database);
$this->db->set_charset("utf8");
}
public function getConnection() {
if ($this->db->connect_errno > 0) {
die('Unable to connect to database [' . $this->db->connect_error . ']');
}
return $this->db;
}
}
如何在单个连接中执行查询
答案 0 :(得分:1)
你应该在循环之外实例化db对象,并在以下之后关闭它:
$con = new db();
$i = 0;
while($i <= 10){
$db = $con->getConnection();
$query = "call rep_summary('$date')";
$result = $db->query($query);
while ($data = $result->fetch_assoc()) {
$user = $data['username'];
$id = $data['id'];
echo $user;
}
$i++;
}
$db->close();
答案 1 :(得分:0)
尝试移动数据库连接并关闭while循环外的函数。您可以在同一连接上执行多个查询。
include 'db.php';
$con = new db();
$db = $con->getConnection();
$date = date('Y-m-d');
$i = 0;
while($i <= 10){
$query = "call rep_summary('$date')";
$result = $db->query($query);
while ($data = $result->fetch_assoc()) {
$user = $data['username'];
$id = $data['id'];
echo $user;
}
$i++;
}
$db->close();