在使用两个mysql查询执行PHP函数时,第二个返回null,这不应该有,因为它们都在phpmyadmin SQL查询子目录中工作。
这是功能:
public static function getStates($countryId) {
try {
$query = "SELECT * FROM `Apostas` WHERE `idConfronto` = ".$countryId;
$result = dbconfig::run($query);
if(!$result) {
throw new exception("Confronto invalido.");
}
$res = array();
while($resultSet = mysqli_fetch_assoc($result)) {
$sql2 = "SELECT * FROM `Mercados` WHERE `idMercado` = ".$resultSet["idMercado"];
$result2 = dbconfig::run($sql2);
if(!$result2) {
throw new exception("Não há mercados.");
}
while ($row2 = mysqli_fetch_assoc($result2)) {
$res[$resultSet['idMercado']] = $row2['nomeMercado'];
}
}
$data = array('status'=>'success', 'tp'=>1, 'msg'=>"States fetched successfully.", 'result'=>$res);
} catch (Exception $e) {
$data = array('status'=>'error', 'tp'=>0, 'msg'=>$e->getMessage());
} finally {
return $data;
}
}
第一个查询每次都有效,但第二个查询会出现“Nãahámercados”异常。
调试函数后,变量$ resultSet [“idMercado”]正在运行,sql查询也可以,但代码会导致异常。
我做错了什么?也许是语法的东西?
- EDIT1: 根据要求,dbconfig :: run的代码:
public static function run($query) {
try {
if(empty($query) && !isset($query)) {
throw new exception("Query string is not set.");
}
$result = mysqli_query(self::$con, $query);
self::close();
return $result;
} catch (Exception $e) {
echo "Error: ".$e->getMessage();
}
}
- EDIT2: 正如Cavid建议的那样,在关闭连接之前完成所有查询,以下是函数的结果:
public static function getStates($countryId) {
try {
$query = "SELECT * FROM `Apostas` WHERE `idConfronto` = ".$countryId;
$result = $conn->query($query);
if(!$result) {
throw new exception("Confronto invalido.");
}
$res = array();
if ($result->num_rows > 0) {
while ($resultSet = $result->fetch_assoc()) {
$sql2 = "SELECT * FROM `Mercados` WHERE `idMercado` = ".$resultSet['idMercado'];
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
while ($row2 = $result2->fetch_assoc()) {
$res[$resultSet['idMercado']] = $row2['nomeMercado'];
}
}
}
}
$data = array('status'=>'success', 'tp'=>1, 'msg'=>"States fetched successfully.", 'result'=>$res);
} catch (Exception $e) {
$data = array('status'=>'error', 'tp'=>0, 'msg'=>$e->getMessage());
} finally {
return $data;
}
$conn->close();
}
它现在给我一个错误代码500“内部服务器错误”
答案 0 :(得分:3)
我建议您加入它们并仅使用一个while循环,而不是进入两个同时具有引用ID的不同表:
public static function getStates($countryId) {
try {
// Inner join both tables
$query = "SELECT a.idMercado, a.idConfronto, b.nomeMercado FROM Apostas AS a ";
$query .= "INNER JOIN ";
$query .= "Mercados AS b ";
$query .= "ON a.idMercado = b.idMercado ";
$query .= "WHERE a.idConfronto = " . $countryId;
$result = dbconfig::run($query);
if(!$result) {
throw new exception("Confronto invalido.");
}
// Results
$res = array();
while ($row = mysqli_fetch_assoc($result)) {
$res[$row['idMercado']] = $row['nomeMercado'];
}
$data = array('status'=>'success', 'tp'=>1, 'msg'=>"States fetched successfully.", 'result'=>$res);
} catch (Exception $e) {
$data = array('status'=>'error', 'tp'=>0, 'msg'=>$e->getMessage());
} finally {
return $data;
}
}