당신은 두 개의 MySQL의 $con
의 같은 변수 이름의 연결뿐만 아니라 $result
& $row
있습니다. 그래서 내부 루프의 변수 이름을 변경하여 충돌하지 않도록하십시오. & 모두 작동해야합니다. $con_inside
, $result_inside
& $row_inside
.
또한 mysqli_query
행에 or die(mysqli_error());
을 추가 했으므로 쿼리가 죽으면 오류가 반환 될 수 있습니다.
<?php
$con = mysqli_connect("localhost","UN","PW","DB");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_SESSION['user']['id'];
$result = mysqli_query($con, "SELECT * FROM favourites WHERE user='$id'") or die(mysqli_error());
while ($row = mysqli_fetch_array($result)) {
$code = $row['gamecode'];
$con_inside = mysqli_connect("localhost","UN","PW","DB");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result_inside = mysqli_query($con_inside, "SELECT * FROM menus WHERE code='$code'") or die(mysqli_error());
while($row_inside = mysqli_fetch_array($result_inside)) {
?>
<a href="<?php echo $row_inside['link']; ?>">
<img src="<?php echo $row_inside['picture']; ?>" alt="<?php echo $row_inside['game']; ?>" height="120" width="150" class="fade"></a>
<?php
}
mysqli_close($con_inside);
}
mysqli_close($con);
여기에 약간 개선 된 버전의 코드가 있습니다. 루프의 내부 DB 연결을 제거했습니다. & 스크립트 맨 위에 설정했습니다. 각 루프에서 연결을 재설정 할 필요는 없습니다. 또한 문자열을 설정하는 대신 mysqli_*
쿼리를 사용하는 기본 방법 인 mysqli_stmt_bind_param
을 사용하여 줄을 추가했습니다. 또한 mysqli_free_result
을 사용하여 각 루프에서 쿼리 메모리를 확보하십시오. 이들은 작은 것들이지만 더 나은 코드를 추가합니다.
<?php
// Main DB connection.
$con = mysqli_connect("localhost","UN","PW","DB") or die(mysqli_connect_error());
// Inside DB connection.
$con_inside = mysqli_connect("localhost","UN","PW","DB") or die(mysqli_connect_error());
// Set the $id variable.
$id = $_SESSION['user']['id'];
// Set the query string.
$query = "SELECT * FROM favourites WHERE user='$id'";
// Bind the values to the query.
mysqli_stmt_bind_param($query, 's', $id);
// Get the result.
$result = mysqli_query($con, $query) or die(mysqli_error());
// Roll through the results.
while ($row = mysqli_fetch_array($result)) {
// Set the $code variable.
$code = $row['gamecode'];
// Set the query string.
$query_inside = "SELECT * FROM menus WHERE code='$code'";
// Bind the values to the query.
mysqli_stmt_bind_param($query_inside, 's', $code);
// Get the result.
$result_inside = mysqli_query($con_inside, $query_inside) or die(mysqli_error());
// Roll through the results.
while($row_inside = mysqli_fetch_array($result_inside)) {
?>
<a href="<?php echo $row_inside['link']; ?>">
<img src="<?php echo $row_inside['picture']; ?>" alt="<?php echo $row_inside['game']; ?>" height="120" width="150" class="fade"></a>
<?php
}
// Free the result set.
mysqli_free_result($result_inside);
// Close the connection.
mysqli_close($con_inside);
}
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
왜 루프에 여러 번 데이터베이스에 연결하고 있습니까? – barell
두 데이터베이스가 있습니다. – Chikn
왜 같은 변수를 사용하고 있습니까? – MorKadosh