好的,所以我尝试创建一个自定义函数,该函数将为最终用户在iframe中回显网站网址。
该脚本必须检查用户是否已经查看过该站点,如果已经看到该站点,则不再显示该站点,而是从数据库中获取另一个站点url等。
到目前为止,这是我想出的:
function get_urls() { require 'config.php'; global $con; global $currentUsername; $con = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname); $query = "SELECT site_url FROM sites WHERE site_url IS NOT NULL"; $result = mysqli_query($con, $query); // Get all the site urls into one array $siteUrls = array(); $index = 0; while($row = mysqli_fetch_assoc($result)) { $siteUrls[$index] = $row; $index++; } $query2 = "SELECT site_url FROM views WHERE user = '$currentUsername' AND site_url IS NOT NULL"; $result2 = mysqli_query($con, $query2); // Get urls the user has already seen into another array $seenUrls = array(); $index = 0; while($row2 = mysqli_fetch_assoc($result2)) { $seenUrls[$index] = $row2; $index++; } // Compare the two arrays and create yet another array of urls to actually show $urlsToShow = array_diff($siteUrls, $seenUrls); if (!empty($urlsToShow)) { // Echo the url to show for the iframe within browse.php and add an entry to the database that the user has seen this site foreach ($urlsToShow as $urlToShow) { echo $urlToShow; $query = "INSERT INTO views VALUES ('', '$currentUsername', '$urlToShow')"; mysqli_query($con, $query); break; } } // Show the allSeen file when all the ads are seen else {echo 'includes/allSeen.php';} mysqli_free_result($result); mysqli_close($con); }
我目前发现了两个错误。首先,$ siteUrls和$ seenUrls都可以,但是当我使用进行比较时,array_diff它将返回一个空数组。
array_diff
其次,脚本不会将站点url写入数据库,因为$urlToShow是数组而不是单个url吗?
$urlToShow
我认为问题出在您的代码中,您正在创建$ siteUrls,$ seenUrls数组。mysqli_fetch_assoc()函数将为您提供结果行作为关联数组。因此,如果您想在while循环中更改某些代码。请修改
while($row = mysqli_fetch_assoc($result)) { $siteUrls[$index] = $row; $index++; }
到
while($row = mysqli_fetch_assoc($result)) { $siteUrls[$index] = $row['site_url']; $index++; }
并且在第二个while循环中。改变这个
while($row2 = mysqli_fetch_assoc($result2)) { $seenUrls[$index] = $row2; $index++; }
while($row2 = mysqli_fetch_assoc($result2)) { $seenUrls[$index] = $row2['site_url']; $index++;
并尝试