PHP实现每3条企业数据后轮询展示不同数据库Banner广告
I'm working on a PHP page that pulls 25 company records from a MySQL database. My goal is to display a banner image after every 3 company names, rotating through all available banners (currently 4, but this number can change). However, my current code only shows the first banner repeatedly instead of rotating through them.
Current Output:
COMPANY 1
COMPANY 2
COMPANY 3
BANNER 1
COMPANY 4
COMPANY 5
COMPANY 6
BANNER 1
COMPANY 7
Desired Output:
COMPANY 1
COMPANY 2
COMPANY 3
BANNER 1
COMPANY 4
COMPANY 5
COMPANY 6
BANNER 2
COMPANY 7
Original Code:
<?php $Records_per_page = 25; //Intervel to show banner $ShowBannerAfter = 3; //Query to get the companies form DB $sqlQuery = "SELECT * FROM company WHERE company_name != '' ORDER BY company_name"; //Query to get the banners form the db. $sqlQueryBanner = "SELECT * FROM banner"; $resultV = mysql_query($sqlQuery); //Number of companies returned $num_rowsV = mysql_num_rows($resultV); //Check if no company is found if ($num_rowsV > 0) { //Looping through company recorde for ($i = 1; $i < $num_rowsV + 1; $i++) { $row = mysql_fetch_array($resultV); //Showing the company to the user. echo "<div>".$row['company_name']."</div>"; //checking if the number of company is less than banner interval. $j = $num_rowsV <= $ShowBannerAfter ? $num_rowsV - 1 : $ShowBannerAfter; //Removing the last '-' form the banner ID session $_SESSION['banID'] = rtrim($_SESSION['banID'],'-'); //array to store all the banner ID $arrBanID = array(); //passing the banner ID form sessionn to array. $arrBanID = explode('-',$_SESSION['banID']); $isBreak = "false"; //This will check to show the banner after every X interval. if($i % $j == 0){ $resultBanner = mysql_query($sqlQueryBanner ); //Number of banner returned $num_rowsB = mysql_num_rows($resultBanner); //Looping through the banner for($k = 0; $k < $num_rowsSB; $k++){ $rowB = mysql_fetch_array($resultBanner); //checking if banner id already exist in the array if(!in_array($rowSB['id'], $arrBanID)){ //if the banner ID not found then this banner should be shown to the user. $isBreak = "true"; //Adding the current banner ID in Session which is shown to user $_SESSION['banID'] = $_SESSION['banID'] . $rowSB['id'] . '-'; }else { //If banner ID found in array dont show to user. $isBreak = "false"; } //Show the banner to user if not found in the array. if($isBreak = "true"){ echo "<img src=" . $rowSB['image_URL'] ."/>"; break; } } } } } ?>
Fixes & Explanation
Your original code had a few issues: variable typos, inefficient repeated database queries for banners, and a session-based logic that was preventing rotation (it was trying to avoid repeating banners instead of cycling through them). Here's the corrected version with a simple, reliable rotation system:
<?php // Start session if not already active if (!session_id()) session_start(); $Records_per_page = 25; $ShowBannerAfter = 3; // Fetch all companies (limit to 25 as specified) $sqlQuery = "SELECT * FROM company WHERE company_name != '' ORDER BY company_name LIMIT $Records_per_page"; $resultV = mysql_query($sqlQuery); $num_rowsV = mysql_num_rows($resultV); // Fetch all banners once and store in an array (way more efficient than querying every time) $banners = []; $sqlQueryBanner = "SELECT * FROM banner"; $resultBanner = mysql_query($sqlQueryBanner); while ($rowB = mysql_fetch_array($resultBanner)) { $banners[] = $rowB; } $totalBanners = count($banners); // Initialize banner index in session if it doesn't exist if (!isset($_SESSION['current_banner_index'])) { $_SESSION['current_banner_index'] = 0; } if ($num_rowsV > 0) { for ($i = 1; $i <= $num_rowsV; $i++) { $row = mysql_fetch_array($resultV); echo "<div>".$row['company_name']."</div>"; // Check if we need to display a banner after this company entry if ($i % $ShowBannerAfter == 0 && $totalBanners > 0) { // Get the current banner from our pre-fetched array $currentBanner = $banners[$_SESSION['current_banner_index']]; echo "<img src='".$currentBanner['image_URL']."' alt='Banner' />"; // Increment index for next banner, loop back to 0 when we reach the end $_SESSION['current_banner_index'] = ($_SESSION['current_banner_index'] + 1) % $totalBanners; } } } ?>
Key Changes:
- Pre-fetch Banners: We query all banners once at the start and store them in an array, eliminating repeated database calls which improves performance.
- Simple Rotation Logic: We use a session variable to track which banner to show next. After each display, we increment the index and use modulo
% $totalBannersto loop back to the first banner once we've cycled through all options. - Fixed Typo Errors: Removed incorrect variable references like
$num_rowsSBand$rowSBthat were breaking your original code. - Simplified Condition: Replaced the overly complex
$jcalculation with a direct check$i % $ShowBannerAfter == 0to know when to display a banner. - Session Safety: Added a check to ensure the session is started before using session variables.
Note: The mysql_* functions are deprecated in PHP 5.5 and removed entirely in PHP 7+. For a secure, modern solution, consider switching to MySQLi or PDO for database interactions.
内容的提问来源于stack exchange,提问作者Siddharth Doshi

